ChrisGordon15
ChrisGordon15

Reputation: 9

How can I parse a string into individual words and sort them in Java?

I am trying to have a user input a line of text and then be able to reorder it. I do not understand how to be able to seperate each word from the input text to be able to use substring and reorder. I don't know how to use array and only have two weeks experience in programming.

Upvotes: 0

Views: 1365

Answers (3)

Bob Kuhar
Bob Kuhar

Reputation: 11140

aix's suggesting to use a regex to split gets the string parsed into an array which has a sort method in javascript.

s = "zero apple watchdog hammer";
s.split( " " ).sort();

...should produce the array...

["apple", "hammer", "watchdog", "zero"]

Its not too different in Java...

String s = "zero apple watchdog hammer";
String[] splits = s.split( " " );
Arrays.sort( splits );
System.out.println( String.format( "splits: %s", Arrays.toString( splits ) ) );

Of course, the regex passed to split can be improved to handle all manner of whitespace. I'll leave that as an exercise for the reader.

Upvotes: 0

Grace Huang
Grace Huang

Reputation: 5699

If you mean JavaScript, not Java, the syntax is a little different from JavaScript

var words = inputStr.replace(/\s+/g, ' ').split(' ');

Where inputStr.replace(/\s+/g, ' ') replaces 1+ whitespaces with 1 whitespace, and split(' ') splits the whitespace delimited string into an array.

Then you can reorder the array based on what you want.

You want to make the reordered array into a string again, use:

var newString = words.join(' ');

Upvotes: 0

NPE
NPE

Reputation: 500703

I do not understand how to be able to seperate each word from the input text

If inputStr is your input string, you can use

String[] words = inputStr.split("\\s+");

This will create an array called words and would populate it with the (space-separated) words of the input string.

String.split() is explained here. If you haven't come across regular expressions, the "\\s+" simply means "one or more spaces".

Upvotes: 3

Related Questions