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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!