LearnFrenzy
Sign in Take a free test

Strings and StringBuilder · Java String Programs · Question 6

Reverse each word but keep the word order in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Reverse the letters of every word in a sentence while keeping the words in their original order and single spaces between them.

Solution
Main.java
public class Main {
    static String reverseWords(String s) {
        String[] words = s.trim().split("\\s+");
        StringBuilder out = new StringBuilder();
        for (String w : words) {
            if (!out.isEmpty()) out.append(' ');
            out.append(new StringBuilder(w).reverse());
        }
        return out.toString();
    }

    public static void main(String[] args) {
        System.out.println(reverseWords("Learn Java with LearnFrenzy"));
        System.out.println(reverseWords("  racecar   level  "));
    }
}

Output Verified by compiling and running

nraeL avaJ htiw yznerFnraeL
racecar level

Each word is reversed independently with a temporary StringBuilder and appended to the result.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links