Given the string “abc123”, how many ways can you think of to reverse the string to get “321CBA”?

This article will show you several common string inversion methods.

Prepare knowledge

Before we look at string inversion, a few background points:

  • The String class is final and immutable;
  • The String class does not provide reverse () method, but the StringBuilder/StringBuffer provides reverse () method;
  • StringBuilder doesn’t have a toCharArray() method, but String does.
  • String provides a charAt method to obtain a char value at the specified index position.

A string is converted to a byte array

The string is converted to an array of Byte [] using the getBytes() method. Create a temporary array with the same length as the string. Reverse order traversal of a byte array obtained from a string, stored in a temporary array. Finally, the array is converted to a String.

@Test public void bytesReverse() { String input = "GeeksforGeeks"; byte[] strAsByteArray = input.getBytes(); byte[] result = new byte[strAsByteArray.length]; For (int I = 0; i < strAsByteArray.length; i++) { result[i] = strAsByteArray[strAsByteArray.length - i - 1]; } System.out.println(new String(result)); }Copy the code

The disadvantages of this approach are also obvious, when the string is Chinese, Japanese and Korean languages, after the inversion is basically meaningless gibberish.

Through the Reverse () method of StringBuilder

String strings do not have a reverse() method, so strings can be built as StringBuilder or StringBuffer, using the Reverse () method of StringBuilder to reverse the String.

@test public void stringBuilderReverse(){StringBuilder sb = new StringBuilder(" 新 "); System.out.println(sb.reverse().toString()); }Copy the code

The Reverse () method of StringBuilder also does a good job of reversing Chinese. StringBuffer is used in the same way as StringBuilder.

String is converted to char array

First convert the string to an array of char, then print or concatenate the data in CHAR in reverse order.

@test public void string2CharReverse(){String input = "new view "; char[] try1 = input.toCharArray(); for (int i = try1.length - 1; i >= 0; i--) { System.out.print(try1[i]); }}Copy the code

The above method is directly printed in reverse order, for the obtained char array concatenation of new string can also be two-way pointer char array characters swap positions.

@test public void string2CharChangeReverse(){String input = "new view "; char[] tempArray = input.toCharArray(); int right = tempArray.length - 1; for (int left = 0; left < right; Char temp = tempArray[left]; char temp = tempArray[left]; tempArray[left] = tempArray[right]; tempArray[right] = temp; } for (char c : tempArray) { System.out.print(c); }}Copy the code

The swap algorithm is very simple, specify the starting position of the left and right Pointers as 0 and Length-1 respectively, and then swap the left and right positions. After swapping left plus one, right minus one, and swapping again until left is no longer less than right.

Once you have the CHAR array, you can also reverse the characters using List and Collections.

@test public void string2CharListReverse(){String input = "new view "; char[] hello = input.toCharArray(); List<Character> trial1 = new ArrayList<>(); for (char c : hello) { trial1.add(c); } Collections.reverse(trial1); for (Character character : trial1) { System.out.print(character); }}Copy the code

The string is also converted to a char array, and then each item in the array is put into a List, which is reversed using the Reverse method of the Collections utility class.

We can also reverse the order of characters in a char array using the first-in-last-out feature of the stack:

@test public void string2Stack() {String STR = "new view "; Stack<Character> s = new Stack<>(); for(int i = 0; i<str.length(); I ++) {// add s.addd (str.charat (I)); } StringBuffer sb = new StringBuffer(); for(int i = 0; i<str.length(); I++) {// unstack sb. Append (s.pop()); } System.out.println(sb); }Copy the code

Through the charAt method

String provides a charAt method that can be used to retrieve characters under a particular index. The charAt() method returns a char value at the specified index position. The index ranges from 0 to length()-1. The parentheses in chartAt() can only transmit parameters of the int type.

@test public void string2CharAt() {String STR = "new view "; for (int i = str.length() - 1; i >= 0; i--) { System.out.print(str.charAt(i)); }}Copy the code

Using the recursive

To reverse a string recursively:

Public static String reverse5(String STR) {int len = str.length(); if (len <= 1) { return str; } String left = str.substring(0, len / 2); String right = str.substring(len / 2, len); return reverse5(right) + reverse5(left); }Copy the code

summary

There are eight ways to reverse a string, summarized above, but not completely covered. For example, you can also reverse a string using the Stringutils.reverse method provided in Apache Commons-Lang3.

In the interview gives this question the main consideration is your knowledge area and the degree that live learns to use flexibly. Also, you may have seen some algorithms and data structures in it.

The interview series

  • Interview questions: Talk about TCP sticky, unpack, and Solutions
  • Interview question: Why does overriding equals usually override hashCode?
  • Interviewer: How to find the longest string in a string without repetition?
  • Don’t Understand Java generics? Just use this article to make sure you have a good interview answer.
  • Interview Question: 8 Ways to Invert a string. What can you Think of?