Reputation: 9
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
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
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
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