-
问题: 给定一个字符串,将字符串前面几个字符移动字符串的末尾
-
解法一:蛮力位移 将需要移动的字符一个一个移到字符串尾部,设字符串的长度为n
原字符串:abchro
java代码如下:
public class ForceMove {
//字符串的长度为n
public String[] LeftShiftOne(String[] s, int n){
//将数组第一个字符赋给T,之后的字符依次前移一位,最后把T的值赋值给数组最后一位s[n-1]
//进行多次循环后可以将所需的若干个字符都移动至字符串末尾
String T = s[0];
for (int i=1; i < n; i++){
s[i-1] = s[i];
}
s[n-1] = T;
return s ;
}
}
public class Demo {
public static void main(String[] args) {
String[] s = new String[]{"a","b","c","h","r","o"};
ForceMove forceMove = new ForceMove();
for (int i =0;i<3;i++) {
forceMove.LeftShiftOne(s, 6);
}
for (int n=0; n<=s.length-1;n++){
System.out.print(s[n]);
}
}
}
hroabc
Process finished with exit code 0