Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse each individual word of "Hello World" string with Java

I want to reverse each individual word of a String in Java (not the entire string, just each individual word).

Example: if input String is "Hello World" then the output should be "olleH dlroW".

like image 338
Vicheanak Avatar asked Mar 14 '10 07:03

Vicheanak


2 Answers

This should do the trick. This will iterate through each word in the source string, reverse it using StringBuilder's built-in reverse() method, and output the reversed word.

String source = "Hello World";  for (String part : source.split(" ")) {     System.out.print(new StringBuilder(part).reverse().toString());     System.out.print(" "); } 

Output:

olleH dlroW  

Notes: Commenters have correctly pointed out a few things that I thought I should mention here. This example will append an extra space to the end of the result. It also assumes your words are separated by a single space each and your sentence contains no punctuation.

like image 116
William Brendel Avatar answered Oct 07 '22 06:10

William Brendel


Know your libraries ;-)

import org.apache.commons.lang.StringUtils;  String reverseWords(String sentence) {     return StringUtils.reverseDelimited(StringUtils.reverse(sentence), ' '); } 
like image 36
JRL Avatar answered Oct 07 '22 06:10

JRL