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
1 2 3 4 5 6 7 8 9 |
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
1 |
Reverse string : moc.deeccus2edoc |
Reverse String character by character using StringBuilder
1 2 3 4 |
String str = "code2succeed.com"; String reverseStr = ""; reverseStr = new StringBuilder(str).reverse().toString(); System.out.println("Reverse string : "+reverseStr); |
Output
1 |
Reverse string : moc.deeccus2edoc |
2) Reverse String word by word
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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
1 |
code2succeed.com in example string Sample |