I have \"Hello World\"
kept in a String variable named hi
.
I need to print it, but reversed.
How can I do this? I understand there
public static String reverseIt(String source) {
int i, len = source.length();
StringBuilder dest = new StringBuilder(len);
for (i = (len - 1); i >= 0; i--){
dest.append(source.charAt(i));
}
return dest.toString();
}
http://www.java2s.com/Code/Java/Language-Basics/ReverseStringTest.htm
I am doing this by using the following two ways:
Reverse string by CHARACTERS:
public static void main(String[] args) {
// Using traditional approach
String result="";
for(int i=string.length()-1; i>=0; i--) {
result = result + string.charAt(i);
}
System.out.println(result);
// Using StringBuffer class
StringBuffer buffer = new StringBuffer(string);
System.out.println(buffer.reverse());
}
Reverse string by WORDS:
public static void reverseStringByWords(String string) {
StringBuilder stringBuilder = new StringBuilder();
String[] words = string.split(" ");
for (int j = words.length-1; j >= 0; j--) {
stringBuilder.append(words[j]).append(' ');
}
System.out.println("Reverse words: " + stringBuilder);
}
I tried, just for fun, by using a Stack. Here my code:
public String reverseString(String s) {
Stack<Character> stack = new Stack<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
stack.push(s.charAt(i));
}
while (!stack.empty()) {
sb.append(stack.pop());
}
return sb.toString();
}
It is very simple in minimum code of lines
public class ReverseString {
public static void main(String[] args) {
String s1 = "neelendra";
for(int i=s1.length()-1;i>=0;i--)
{
System.out.print(s1.charAt(i));
}
}
}
One natural way to reverse a String
is to use a StringTokenizer
and a stack. Stack
is a class that implements an easy-to-use last-in, first-out (LIFO) stack of objects.
String s = "Hello My name is Sufiyan";
Put it in the stack frontwards
Stack<String> myStack = new Stack<>();
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens()) {
myStack.push(st.nextToken());
}
Print the stack backwards
System.out.print('"' + s + '"' + " backwards by word is:\n\t\"");
while (!myStack.empty()) {
System.out.print(myStack.pop());
System.out.print(' ');
}
System.out.println('"');
It gets the value you typed and returns it reversed ;)
public static String reverse (String a){
char[] rarray = a.toCharArray();
String finalvalue = "";
for (int i = 0; i < rarray.length; i++)
{
finalvalue += rarray[rarray.length - 1 - i];
}
return finalvalue;
}