JDK's approach:
1 String str =2new StringBuilder (str). reverse (). toString ();
Achieve yourself:
1 Public classstringdemo{2 Public Static voidMain (string[] args) {3System.out.println (Reverse ("Hello world!"));//!dlrow Olleh4 }5 Public Staticstring Reverse (String str) {6 Char[] Arrs =Str.tochararray ();7 Chartemp = ';8 for(inti = 0, j = arrs.length-1; I < J; i++,j--){9temp =Arrs[i];TenArrs[i] =Arrs[j]; OneARRS[J] =temp; A } -StringBuilder SB =NewStringBuilder (); - for(CharS:arrs) { the Sb.append (s); - } - returnsb.tostring (); - } + } - + Public voidReverse2 (FinalString str) { A Char[] chars =Str.tochararray (); atStringBuilder SB =NewStringBuilder (); - for(inti = chars.length-1;i>0; i--){ -Sb.append (Char[i]); - } - returnsb.tostring (); -}
* "I love China", reverse the character and turn it into "China love I"
Method One: one character for one character change
1 Public classStringreverse {2 3 Public voidSwapChar[] arr,intBeginintend) {4 while(Begin <end) {5 Chartemp =Arr[begin];6Arr[begin] =Arr[end];7Arr[end] =temp;8begin++;9end--;Ten } One } A Publicstring Swapwords (String str) { - Char[] arr =Str.tochararray (); -Swap (arr, 0, Arr.length-1); the intBegin = 0; - for(inti = 1; i < arr.length; i++) { - if(Arr[i] = = ") { -Swap (arr, begin, I-1); +begin = i + 1; - } + } A at return NewString (arr); - } - Public Static voidMain (string[] args) { -String str = "I love java"; -System.out.println (Newstringreverse (). Swapwords (str)); - } in}
Method Two: (using the method provided by the JDK)
1 Public classMain {2 Public Static voidMain (string[] args) {3Scanner sc =NewScanner (system.in);4String str =sc.nextline ();5string[] SArr = Str.split ("");//I Love Java6list<string> list =arrays.aslist (SARR);7 collections.reverse (list);8 for(String word:list) {9System.out.print (word+ "");Ten } One } A}
Method 3: Change a word by one word
1 Public classstringdemo{2 Public Static voidMain (string[] args) {3System.out.println (Reverse ("Hello world!"));//world! Hello4 }5 Public Staticstring Reverse (String str) {6String [] Arrs = Str.split ("");7String temp = "";8 for(inti = 0, j = arrs.length-1; I < J; i++, j--){9temp =Arrs[i];TenArrs[i] =Arrs[j]; OneARRS[J] =temp; A } -StringBuilder SB =NewStringBuilder (); - for(String s:arrs) { theSb.append (s). Append (""); - } - returnsb.tostring (); - } +}
Inverse of a string