How to Reverse a String Word by Word in Java?

There are multiple way to Reverse a String Word by Word in Java.

using StringBuilder() method:-

  • Here we are using reverse(), split() and substring() methods to reverse each word.
  • From split(“\\s”) method, we can get all words in an array.
  • Now traverse each word from for loop.
  • Create String builder object and pass each word.
  • Now we can reverse each word from reverse() method of StringBuilder class.
  • Convert each word in string from toString() method.
  • Print each reverse word.             

Using for loop method :-

  • From split(” “) method, we can get all words in an array.
  • Now traverse each word from for loop.
  • Convert each word in character array and store in char c[].
  • Starting from last word of words array, append each word to c[j] variable.
  • Print each word  from System.out.print(c[j]);
				
					public class ReverseEachWord {
	public static void main(String[] args) {
		String str = "java spring hibernate";

		System.out.println("using string builder with reverse method :- " + reverseWordByWord(str));

		System.out.println("using for loop with reverse method:- ");
		String s[] = str.split(" ");
		for (int i = 0; i < s.length; i++) {
			char c[] = s[i].toCharArray();
			for (int j = c.length - 1; j >= 0; j--) {
				System.out.print(c[j]);
			}
			System.out.print(" ");
		}
	}

	public static String reverseWordByWord(String st) {
		String word[] = st.split("\\s");
		String reverseWord = "";
		for (String str : word) {
			StringBuilder sb = new StringBuilder(str);
			sb.reverse();
			reverseWord += sb.toString() + " ";
		}
		return reverseWord.trim();
	}
}

				
			

Output :-
using string builder with reverse method :- avaj gnirps etanrebih
using for loop with reverse method:-
avaj gnirps etanrebih