Without going through the char sequence is there any way to reverse String
in Java
You may use StringBuilder..
String word = "Hello World!";
StringBuilder sb = new StringBuilder(word);
System.out.print(sb.reverse());
Use StringBuilder's
or StringBuffer's
method... reverse()
public class StringReverse
{
public static void main(String[] args)
{
String string=args[0];
String reverse = new StringBuffer(string).reverse().toString();
System.out.println("\nString before reverse: "+string);
System.out.println("String after reverse: "+reverse);
}
}
StringBuffer
is thread-safe, where as StringBuilder
is Not thread safe..... StringBuilder
was introduced from Java 1.5, as to do those operations faster which doesn't have any Concurrency to worry about....
Try reverse() method:
StringBuilder stringName = new StringBuilder();
String reverse = stringName.reverse().toString();
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);
}
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;
}
Here I have a sample of the same using substring method and o(n) without using any nethods from string . I am aware that using substring will hold complete string memory.
for(int i = 0; i < s.length(); i++) {
s = s.substring(1, s.length() - i) + s.charAt(0) + s.substring(s.length() - i);
System.out.println(s);
}
This might help you!!