java调整字符串-CSDN博客

88 阅读1分钟
package 字符串练习;

public class 调整字符串 {
    /* 如果调整成功则给提示,返回不成功也给提示

       调整 例如:abcde -> bcdea -> cdeab 就是把第一个值放到最后的位置上
       现在是给定两个字符串, 选定其中一个进行调整, (我们想一下,如果调整字符串的长度次,那不就是返回到原来的字符串了吗,所以调整是可以有固定次数的)
     */
    public static void main(String[] args) {
        String str = "abcde";
        String str_result = "cedab";

        char[] str_char_array = str.toCharArray();
        char[] str_result_char_array = str_result.toCharArray();
        int signs = 0;

        for (int i = 0; i < str.length(); i++) {
            char sign = str_char_array[0];//记录头索引的值

            swap_Position(str,str_char_array);

            str_char_array[str_char_array.length - 1] = sign;//把头索引的值给最后索引位置上

            String new_char_str = new String(str_char_array);//把数组转换成字符串
            if(new_char_str.equals(str_result)){
                signs = 1;
                System.out.println("完毕,可以转换");
                break;
            }
            str_char_array = new_char_str.toCharArray();
        }

        if (signs == 0) {
            System.out.println("不可转换");
        }
    }


    public static void swap_Position(String str,char[] str_char_array ){
        for (int j = 0; j < str.length() - 1; j++) {
            str_char_array[j] = str_char_array[j+1];
        }//交换位置
    }
}