Record two methods to achieve string reverse order:
The first method is more violent, through The subscript of the string reverses the string. The substring() method of the String class is used here. This method is more commonly used, so I won’t write it down in detail.
The second method is Convert theString
class into theStringBuffer
class, and reverse the string by calling the reverse() method of the StringBuffer class. This method is relatively simple
The following is the implementation code of the two methods:
public class test_2_13 { public static void main(String[] args) { // TODO Auto-generated method stub String a = "123456"; String one = ""; String two = ""; // 方法一: for (int i = 0; i < a.length(); i++) { one += a.substring(a.length() - 1 - i, a.length() - i); } // 方法二: StringBuffer stringBuffer = new StringBuffer(a); two = stringBuffer.reverse().toString(); System.out.println("方法一输出效果:" + one); System.out.println("方法二输出效果:" + two); } }
##Description:
Convert a The contents of the string str are reversed and output.
Data range:1 \le len(str) \le 10000\1≤len(str)≤10000
Input description:
Input a string, there can be spaces
Output description:
Output the string in reverse order
Example 1
Input:
I am a student
Copy Output:
tneduts a ma I
Example 2
Input:
nowcoder
Copy output:
redocwon2. Code implementation
import java.util.*; public class Main { private String reverse(String str) { StringBuilder res = new StringBuilder(str); return res.reverse().toString(); } public Main() { Scanner in = new Scanner(System.in); while (in.hasNextLine()) { String str = in.nextLine(); String res = reverse(str); System.out.println(res); } } public static void main(String[] args) { Main solution = new Main(); } }
The above is the detailed content of Example analysis of Java string reverse order method. For more information, please follow other related articles on the PHP Chinese website!