思路:
將字符串變成數組,對數組反轉
將反轉后的數組變成字符串
只要將反轉的部分的開始和結束的位置作為參數傳遞即可
復制代碼代碼如下:
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;
}
}