Reverse each word of a string using StringBuilder in java (example)

  • Given a string in java, reverse each word of string using StringBuilder in java.
  • Let us look into couple of examples to understand problem statement.
    • Example 1:
      • String inputString = “live star war”
      • reverse(inputString) should be “evil rats raw”
    • Example 2:
      • String inputString = “live desserts”
      • reverse(inputString) should be “evil stressed”

Algorithm: reverse each word of string in java (with example)

  1. Split each word of input string using space delimiter
  2. Reverse each word (result of step 1).
  3. Concatenate words after reversing each word.
  4. We will get our desired output.
reverse each word string java example
Fig 1: Reverse each word of string

Program: reverse a string word by word in java (example)

package org.learn;

import java.util.Scanner;
import java.util.regex.Pattern;

public class ReverseEachWordsInString {

 public static void main(String[] args) {
  try (Scanner scanner = new Scanner(System.in)) {
   System.out.printf("1. Enter string to reverse : ");
   String inputString = scanner.nextLine();
   
   if (inputString == null || inputString.length() == 0) {
    System.out.println("Enter the valid string");
    return;
   }
   
   String reverse = reverseEachWordInString(inputString);
   System.out.printf("2. Reverse string is : %s", reverse);
  }
 } 
 
 private static String reverseEachWordInString(String inputString) {
  String[] arrString = inputString.trim().split(Pattern.quote(" "));
  StringBuilder builder = new StringBuilder();
  int length = arrString.length;

  int index = 0;
  while (index < length) {
   StringBuilder eachWord = new StringBuilder(arrString[index]).reverse();
   builder.append(eachWord).append(" ");
   index++;
  }

  return builder.toString().trim();
 }
}

Output: reverse each word of string in java using Stack & StringBuilder

1. Enter string to reverse : live star war
2. Reverse string is : evil rats raw 

1. Enter string to reverse : live desserts
2. Reverse string is : evil stressed 
Scroll to Top