-5

How can I seperate words in a sentence and I want it by using for or while statements and with using which methods, I don't know exactly. For example, our string is "one two three four". I want it sorted as an output like below;

one
two
three
four
  • 6
    By "sorting" do you mean "replace spaces by linebreaks"? – Kerrek SB Jan 04 '12 at 21:49
  • you want to take a string and display it as an unordered list in alphabetical order? – Brian Jan 04 '12 at 21:49
  • I don't want it in an alphabetical order, just seperate each word from the string – Petr Mitrichev Jan 04 '12 at 21:50
  • 8
    That's not sorting, that's tokenizing. – Fred Foo Jan 04 '12 at 21:50
  • @Brian: I'm curious, how's an "unordered list in alphabetical order" possible? – Mac Jan 04 '12 at 21:51
  • Where are talking about an split? or we want to do anything more? – jenaiz Jan 04 '12 at 21:53
  • I asked it because nobody could have answered my first question, I've just wanted to examine that: is anybody in stackoverflow that able to give me an idea about that easy query – Petr Mitrichev Jan 04 '12 at 21:56
  • @Mac anything in
      and
    • tags can be sorted in whatever order you like via javascript. unordered list in html terms is referring to the styling not the actual sorting.
    – Brian Jan 04 '12 at 22:57
  • @Brian: very true, I hadn't considered the term "unordered" in that manner, mostly because the question has nothing to do with HTML (or markup of any kind really)... – Mac Jan 05 '12 at 00:38

2 Answers2

3
String newStr = oldStr.replaceAll(" ", "\n");
System.out.println(newStr);
Mac
  • 14,615
  • 9
  • 62
  • 80
  • For extra robustness, check out [this question](http://stackoverflow.com/q/247059/436282) for tips on newlines. – Andrew Jan 04 '12 at 21:55
2

Here is a point to start:

String text = "one two three four";
String[] words = text.split(" ");
// Now implement any sorting algorithm on the array "words"
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417