String reversal in java is a common topic, so today I will summarize what are the methods of reversing strings in java:
1. Use the method reverse() in the java library function
private static String reverse1(String s) {
StringBuilder st=new StringBuilder(s);
return st.reverse().toString();
}
2. Convert to character array for splicing:
private static String reverse2(String s){
char[] ch=s.toCharArray();
StringBuilder sb=new StringBuilder("");
for(int i=s.length()-1;i>=0;i--){
sb.append(ch[i]);
}
return sb.toString();
}
3. Use charAt() function to splice
private static String reverse3(String s){
StringBuilder sb=new StringBuilder("");
for(int i=s.length()-1;i>=0;i--){
sb.append(s.charAt(i));
}
return sb.toString();
}
4. Use the + operator (but it will waste memory):
private static String reverse4(String s){
String s1="";
for(int i=s.length()-1;i>=0;i--){
s1=s1+s.charAt(i);
}
return s1;
}
Finally, call these four functions separately
public static void main(String[] args) {
String s="abcdef";
String s1="abcdef";
System.out.println(reverse1(s));
System.out.println(reverse2(s1));
System.out.println(reverse3(s));
System.out.println(reverse4(s));
}
Results show:
In fact, there are many methods, for example, you can also use collections and the like, but it is a little overkill, so only four are summarized.