Without going through the char sequence is there any way to reverse String
in Java
You can use the StringBuilder#reverse() method:
String reverse = new StringBuilder(originalString).reverse().toString();
Try reverse() method:
StringBuilder stringName = new StringBuilder();
String reverse = stringName.reverse().toString();
If we have to do it:
Without going through the char sequence
One easy way with iteration will be:
public String reverse(String post) {
String backward = "";
for(int i = post.length() - 1; i >= 0; i--) {
backward += post.substring(i, i + 1);
}
return backward;
}
Using minimal API support. A simple algorithm.
static String reverse(String str) {
char[] buffer = str.toCharArray();
for (int i = 0; i < buffer.length/2; ++i){
char c = buffer[i];
buffer[i] = buffer[buffer.length-1-i];
buffer[buffer.length-1-i] = c;
}
return new String(buffer);
}
public class RevString {
public static void main(String[] args) {
String s="jagan";
String rev="";
for (int i=s.length()-1;i>=0;i--) {
rev=rev+s.charAt(i);
}
System.out.println("Reverse String is: "+rev);
}
}
Try this,
String s = "responses";
StringBuilder builder = new StringBuilder(s);
System.out.println(builder.reverse());