In Java, if you want to output strings in reverse order, you can usually sample the head and tail bidirectional loops, one-way loops, or StringBuffer, StringBuilder to achieve. The corresponding sample codes are given below.
Example code 1 - bidirectional loop from end to end :
private static String reverse(String str) {
if (str == null) {
return null;
}
char[] chars = str.toCharArray();
for (int start = 0, end = chars.length - 1; start <= end; start++, end--) {
char tempChar = chars[start];
chars[start] = chars[end];
chars[end] = tempChar;
}
return String.valueOf(chars);
}
The above code adopts the idea of bidirectional looping at the beginning and end, and realizes the exchange of two characters by means of temporary variables. In addition to the head-to-tail bidirectional traversal method, a unidirectional traversal method can also be used to reverse the string.
Sample Code 2 - One-Way Loop
private static String reverse(String str) {
if (str == null) {
return null;
}
int length = str.length();
char[] chars = new char[length];
for (int i = 0; i < length; i++) {
chars[i] = str.charAt(length - i - 1);
}
return String.valueOf(chars);
}
In addition to using the loop method, you can also use the reverse() method of StringBuilder or StringBuffer to reverse the string.
Sample Code 3 - StringBuilder or StringBuffer
private static String reverse(String str) {
if (str == null) {
return null;
}
return new StringBuilder(str).reverse().toString();
}
or
private static String reverse(String str) {
if (str == null) {
return null;
}
return new StringBuffer(str).reverse().toString();
}
Test verification
public static void main(String[] args) {
System.out.println(reverse("abcd"));
System.out.println(reverse("A1B2C3"));
}
The output is as follows:
dcba
3C2B1A
For more knowledge points related to Java interviews, you can pay attention to the [Java Interview Manual] applet, which involves Java foundation, multithreading, JVM, Spring, Spring Boot, Spring Cloud, Mybatis, Redis, database, data structure and algorithm.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。