思路:
将字符串变成数组,对数组反转
将反转后的数组变成字符串
只要将反转的部分的开始和结束的位置作为参数传递即可
复制代码代码如下:
class reverse_String{
public static void main (String[] args){
String s1 = " java php .net ";
String s2 = reverseString(s1);
System.out.println(s2);
}
public static void reverseString(String str, int start, int end){
char[] chs = str.toCharArray();//字符串变数组
reverseArray(chs,start,end);//反转数组
retrun new String(chs);//将数组变字符串
}
public static void reverseString(String str){
retrun reverseString(str,0,str.length());
}
public static void reverseArray(char[] arr,int x , int y){
for(int start = x,end=y-1; start<end; start++,end--){
swap(arr,start,end);
}
}
private static void swap(char[] arr,int x ,int y){
char temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
}