views:

848

answers:

11

Hello I want to do reverse each word of the String in Java example if input String is "Hello World" then the output should be "olleH dlroW".

+6  A: 

You need to do this on each word after you split into an array of words.

public reverse(String word) {
    char[] chs = word.toCharArray();

    int i=0, j=chs.length-1;
    while (i < j) {
        // swap chs[i] and chs[j]
        char t = chs[i];
        chs[i] = chs[j];
        chs[j] = t;
       i++; j--;
    }
}
fastcodejava
This will not work if there are surrogate pairs in the text.
Péter Török
Could you explain more?
fastcodejava
@fastcodejava - surrogate pairs are a feature of unicode, in which (if I understand correctly) instead of 16 bits forming one unicode character, you get a pair of 16bit characters forming one character. Google for "surrogate pair" for more info.
CPerkins
A: 

Heres a method that takes a string and reverses it.

public String reverse ( String s ) {
            int length = s.length(), last = length - 1;
            char[] chars = s.toCharArray();
            for ( int i = 0; i < length/2; i++ ) {
                char c = chars[i];
                chars[i] = chars[last - i];
                chars[last - i] = c;
            }
            return new String(chars);
        }

First you need to split the string into words like this

String sample = "hello world";  
String[] words = sample.split(" ");  
Zaki
A: 

use java StringBuffer.reverse()

String[] toks = new String("Hellow World");
for (String s : toks)
{
    StringBuffer sb = new StringBuffer(s);
    sb.reverse();

    System.out.print(sb);
}
Eric
you should split the string into words before reverse it
Anantha Kumaran
This doesn't solve the OP's problem. It reverses the words as well as the letters in each word.
Stephen C
+17  A: 

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

String source = "Hello World";

for (String part : source.split(" ")) {
    System.out.print(new StringBuffer(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.

William Brendel
It sounds like a homework, using built-in methods are not acceptable.
fastcodejava
+1 just wanted to answer this. Note that you have an excess blank at the end
Peter Kofler
Probably, but I'll leave this answer here since the question didn't specify whether it is homework-related.
William Brendel
Nit pick - an extra space is added at the end, and multi-space separators are turned into single spaces.
Stephen C
@fastcodejava - in some peoples' minds, complete answers to homework questions are unacceptable ... cos' ultimately it doesn't help the OP.
Stephen C
My solution preserves all white spaces, doesn't use any "advanced" string manipulation procedures, and doesn't even use any loop. It should be instructive.
polygenelubricants
A: 
public static void main(String[] args) {
        System.out.println(eatWord(new StringBuilder("Hello World This Is Tony's Code"), new StringBuilder(), new StringBuilder()));
    }
static StringBuilder eatWord(StringBuilder feed, StringBuilder swallowed, StringBuilder digested) {
    for (int i = 0, size = feed.length(); i <= size; i++) {
        if (feed.indexOf(" ") == 0 || feed.length() == 0) {
            digested.append(swallowed + " ");
            swallowed = new StringBuilder();
        } else {
            swallowed.insert(0, feed.charAt(0));
        }
        feed = (feed.length() > 0)  ? feed.delete(0, 1) : feed ;
    }
    return digested;
}

run:

olleH dlroW sihT sI s'ynoT edoC 
BUILD SUCCESSFUL (total time: 0 seconds)
ZZcat
+6  A: 

Here's the simplest solution that doesn't even use any loops.

public class olleHdlroW {
    static String reverse(String in, String out) {
        return (in.isEmpty()) ? out :
            (in.charAt(0) == ' ')
            ? out + ' ' + reverse(in.substring(1), "")
            : reverse(in.substring(1), in.charAt(0) + out);
    }
    public static void main(String args[]) {
        System.out.println(reverse("Hello World", ""));
    }
}

Even if this is homework, feel free to copy it and submit it as your own. You'll either get an extra credit (if you can explain how it works) or get caught for plagiarism (if you can't).

polygenelubricants
Could you explain in more detail? Seems to complicated.
fastcodejava
Hint: think WHAT instead of HOW.
polygenelubricants
I guess this solution goes to the possible lisp homework, only implemented in java :)
Azder
a recursive loop is still a loop ;)
Jorn
@Jorn :But the code looks great!
ZZcat
There are a lot of inputs that would make this code throw an exception.
Yishai
@Tony, for some definitions of "great", sure it does ;)
Jorn
@Yishai: share some with us.
polygenelubricants
@polygenlubricants, sorry, my mistake, I should have double checked the substring javadocs before commenting. A substring == the length of the string returns an empty string, I thought it threw an exception at >= length of the string.
Yishai
+17  A: 

Obviously:

if( input.equals("Hello world") ){
    System.out.println("olleH dlrow");
}
jrockway
Wtf, what if it is "World Hello"?
fastcodejava
@fastcodejava, if(input.equals("World Hello")){ System.out.println("dlroW olleH");}
Zaki
Great answer, @zaki.
fastcodejava
A: 

Use a for-loop to get each character in the string as you need them, and collect them in a StringBuffer with the add() method.

Thorbjørn Ravn Andersen
+11  A: 

Know your libraries ;-)

import org.apache.commons.lang.StringUtils;

String reverseWords(String sentence) {
    return StringUtils.reverseDelimited(StringUtils.reverse(sentence), ' ');
}
JRL
+1  A: 

Taking into account that the separator can be more than one space/tab and that we want to preserve them:

public static String reverse(String string)
{
    StringBuilder sb = new StringBuilder(string.length());
    StringBuilder wsb = new StringBuilder(string.length());
    for (int i = 0; i < string.length(); i++)
    {
        char c = string.charAt(i);
        if (c == '\t' || c == ' ')
        {
            if (wsb.length() > 0)
            {
                sb.append(wsb.reverse().toString());
                wsb = new StringBuilder(string.length() - sb.length());
            }
            sb.append(c);
        }
        else
        {
            wsb.append(c);
        }
    }
    if (wsb.length() > 0)
    {
        sb.append(wsb.reverse().toString());
    }
    return sb.toString();

}
Mikel
+1  A: 

I'm assuming you could just print the results (you just said 'the output should be...') ;-)

String str = "Hello World";
for (String word : str.split(" "))
    reverse(word);

void reverse(String s) {
    for (int idx = s.length() - 1; idx >= 0; idx--) 
        System.out.println(s.charAt(idx));
}

Or returning the reversed String:

String str = "Hello World";
StringBuilder reversed = new StringBuilder();
for (String word : str.split(" ")) {
  reversed.append(reverse(word));
  reversed.append(' ');
}
System.out.println(reversed);

String reverse(String s) {
  StringBuilder b = new StringBuilder();
  for (int idx = s.length() - 1; idx >= 0; idx--)
      b.append(s.charAt(idx));
  return b.toString();
}
bpfurtado