Java string inversion sample share
- 2020-04-01 02:44:47
- OfStack
Ideas:
Turn the string into an array and reverse the array
Turns the inverted array into a string
Simply pass the starting and ending positions of the inverted part as parameters
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();//String variable set
reverseArray(chs,start,end);//Inversion array
retrun new String(chs);//Converts the array to a string
}
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;
}
}