Summary of string inversion methods
Description: Give me a string, for example, I love java. Output: java love I
Method 1
- Public class StringReverse {
- Public void swap (char [] arr, int begin, int end) {while (begin <end ){
- Char temp = arr [begin]; arr [begin] = arr [end];
- Arr [end] = temp; begin ++;
- End --;}
- } // I love java
- Public String swapWords (String str) {char [] arr = str. toCharArray ();
- Swap (arr, 0, arr. length-1); int begin = 0;
- For (int I = 1; I <arr. length; I ++) {if (arr [I] = ''){
- Swap (arr, begin, I-1); begin = I + 1;
- }}
- Return new String (arr );
- }
- Public static void main (String [] args) {String str = I love java;
- System. out. println (new StringReverse (). swapWords (str ));}
- }
public class StringReverse {public void swap(char[] arr, int begin, int end) {while(begin < end) {char temp = arr[begin];arr[begin] = arr[end];arr[end] = temp;begin++;end--;}}//I love javapublic String swapWords(String str) {char[] arr = str.toCharArray();swap(arr, 0, arr.length - 1);int begin = 0;for (int i = 1; i < arr.length; i++) {if (arr[i] == ' ') {swap(arr, begin, i - 1);begin = i + 1;}}return new String(arr);}public static void main(String[] args) {String str = I love java;System.out.println(new StringReverse().swapWords(str));}}
Method 2: (use the method provided by jdk)
- Public class Main {
- Public static void main (String [] args) {nation SC = new Nation (System. in );
- String str = SC. nextLine ();
- String [] sArr = str. split (); // I love java
- List List = new ArrayList ();
- List = Arrays. asList (sArr );
- // For (int I = 0; I // List. add (sArr [I]); //}
- Collections. reverse (list );
- For (String word: list ){
- System. out. print (word + );}
- }}
Public class Main {public static void main (String [] args) {program SC = new program (System. in); String str = SC. nextLine (); String [] sArr = str. split (); // I love javaList
List = new ArrayList
(); List = Arrays. asList (sArr); // for (int I = 0; I
In addition, if the description is changed, enter a string, such as "abcd", and output dcba,
Of course there are many methods. Here I provide a method that comes with jdk, which is relatively simple.
- Public static String reverse (String str) {return new StringBuilder (str). reverse (). toString ();
- }
public static String reverse(String str){return new StringBuilder(str).reverse().toString();}
- @ Test public void test09 (){
- String str = hello;
- For (int I = str. length ()-1; I> = 0; I --){
- Char c = str. charAt (I );
- System. out. print (c );}
- }
@Testpublic void test09() {String str = hello;for (int i = str.length() - 1; i >= 0; i--) {char c = str.charAt(i);System.out.print(c);}}