Reverse String in Java Example

Reverse String in Java Example

We often come across a situation, where we have to reverse String. In some situation we have to reverse String character by character while in some situations we have to reverse String word by word. Let us see examples.

1) Reverse String character by character

String str = "code2succeed.com";
String reverseStr = "";
int strLength = str.length() - 1;
for(int i=strLength; i>=0; i--) {
	char ch = str.charAt(i);
	reverseStr += ch;
}
		
System.out.println("Reverse string : "+reverseStr);

Output

Reverse string : moc.deeccus2edoc

Reverse String character by character using StringBuilder

String str = "code2succeed.com";
String reverseStr = "";
reverseStr = new StringBuilder(str).reverse().toString();
System.out.println("Reverse string : "+reverseStr);

Output

Reverse string : moc.deeccus2edoc

2) Reverse String word by word

String str = "Sample string example in code2succeed.com";
String [] tokens = str.split("\\s+");
Stack stack = new Stack();
for(String token : tokens) {
	stack.push(token);
}
		
StringBuilder sb = new StringBuilder();
while(!stack.isEmpty()) {
	sb.append(stack.pop()+" ");
}
		
System.out.println(sb.toString());

Output

code2succeed.com in example string Sample

Leave a Reply

Your email address will not be published. Required fields are marked *