This article discusses Java programs to:
- Reverse each word in a String in Java
- Reverse order of words in a String in Java
Reverse order of words in a String
public static void reverseStringByWord(String originalString) { StringBuilder result = new StringBuilder(); String[] words = originalString.split("\\s+"); for (int i = words.length - 1 ; i>=0; i--) { result.append(words[i]).append(' '); } System.out.println("String in reverse order of words: " + result.toString().trim()); }
Reverse each word in a String
private static void reverseEachWord(String originalString){ String[] words = originalString.split("\\s+"); String reverseString = ""; for(int i=0;i<words.length;i++){ String word = words[i]; String reverseWord = new StringBuilder(word).reverse().toString(); reverseString += " " + reverseWord ; } System.out.println("String with each word reversed: " + reverseString); }
If you don’t want to use the StringBuilder reverse() function, refer this article for the corresponding algorithm :
Here is the complete program :
package com.topjavatutorial; public class StringReversal { public static void main(String[] args) { String originalString = "Hello World"; System.out.println("Original String : " + originalString); // String with each word reversed reverseStringByWord(originalString); // String in reverse order of words reverseEachWord(originalString); } private static void reverseEachWord(String originalString) { String[] words = originalString.split("\\s+"); String reverseString = ""; for (int i = 0; i < words.length; i++) { String word = words[i]; String reverseWord = new StringBuilder(word).reverse().toString(); reverseString += " " + reverseWord; } System.out.println("String with each word reversed: " + reverseString); } public static void reverseStringByWord(String originalString) { StringBuilder result = new StringBuilder(); String[] words = originalString.split("\\s+"); for (int i = words.length - 1; i >= 0; i--) { result.append(words[i]).append(' '); } System.out.println("String in reverse order of words: " + result.toString().trim()); } }
Output :
Original String : Hello World
String in reverse order of words: World Hello
String with each word reversed: olleH dlroW
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post
#