-5

Possible Duplicate:
Reverse a given sentence in java

what is the simple way to reverse the words in string in java? Example: "Hello Stack over flow" will turn to: "flow over Stack Hello"

Thank you,

Community
  • 1
  • 1
nabil
  • 904
  • 3
  • 12
  • 28
  • There are several solutions in [this question](http://stackoverflow.com/questions/2713655/reverse-a-given-sentence-in-java). – Blastfurnace Feb 26 '12 at 23:42
  • [Reverse string java](http://chinmaylokesh.wordpress.com/2011/01/19/program-to-reverse-words-in-a-sentence-c-and-java/). – RanRag Feb 26 '12 at 23:48

3 Answers3

1

Here is a simple solution:

    String s = "Hello stack over flow";
    List< String > words = Arrays.asList( s.split( " " ) );
    Collections.reverse( words );
    String reversed = words.get( 0 );
    for ( int i = 1; i < words.size(); ++i ) {
        reversed += " " + words.get( i );
    }

I assume that all characters except spaces are considered as part of words. You may need to provide more details if you need something else.

abresas
  • 835
  • 6
  • 7
1

String s="abcd";

StringBuffer sb=new StringBuffer(s);

sb=sb.reverse();

System.out.println(sb.toString());

Hope can help you.

Tube
  • 21
  • 4
0

A straightforward solution would be splitting the input string at the whitespaces, then reversing the result array with eg. Collections.reverse() or Commons ArrayUtils.reverse(), then joining them back together.

xea
  • 1,204
  • 12
  • 23