Xiaofan encountered a string inversion output problem before, and then found several ways.
First of all, a simple case is that a string of characters is output reversely, without considering others. This is relatively simple:
1. Turn the string into an array, and then output in reverse order:
public void StringRevers(String str) { // Convert string str to character array char[] arr = str.toCharArray(); for(int i = arr.length - 1; i >=0 ; i--) { System.out.print(arr[i]); } }
Of course, this may not be satisfactory. You can also splice strings in reverse order:
public void StringRevers(String str) { // Output after the string str is inverted into a string for(int i = arr.length - 1; i >=0 ; i--) { char c = str.charAt(i); System.out.println(c); } }
Use StringBuffer's own method to implement:
public void StringRevers(String str) { if(str == null || str.length()<=1){ return str; } return new StringBuffer(str).reverse().toString(); }
However, the above method only implements the inverse output of string, but it is not applicable to sentences.
If we want to implement "I Love ShangHai" for sentence class "I Love ShangHai", the above method will find that it cannot be implemented.
1, First, the string is inverted and then the phenomenon "ShangHai Love I" is inverted according to the word:
// Reverse substitution for array 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--; } } public String swapWords(String str) { char[] arr = str.toCharArray(); // Reverse substitution for string array swap(arr, 0, arr.length - 1); int begin = 0; // For array traversal, replace the previous words with "Love" when the space is encountered, such as "evoL" for (int i = 1; i < arr.length; i++) { if (arr[i] == ' ') { swap(arr, begin, i - 1); begin = i + 1; } } // Return character array and string (ShangHai Love I) return new String(arr); }
2. Using split method to generate word array from string sentences according to words:
public void StringRevers(String str) { String[] sArr = str.split(" "); List<String> list = new ArrayList<String>(); list = Arrays.asList(sArr); Collections.reverse(list); for(String word:list){ System.out.print(word+" "); } }
Of course, the list can also be used to directly traverse the array output:
public void StringRevers(String str) { String[] sArr = str.split(" "); for(int i = sArr.length - 1; i >= 0; i--){ System.out.print(sArr[i] + " "); }
Personal feeling method one is more rigorous, because the second one will output an extra space at the end, which can be realized if the code is optimized a little more.