简体   繁体   中英

Split a String into words

I'm looking for some help with creating an array from user String input. I tried with the Split(" ") but as far as I know Scanner deletes the spaces between the words so that didn't work.

Again I'm looking to create an array which would have single words in every "space". So if the user input is:

"My name is John"

the array would look like this:

array[0] = My
array[1] = name
array[2] = is

and so on

Use scanner.nextLine() See nextLine() and then use following:

String urString = scanner.nextLine();
String[] array = urString .split(" ");

You can use urString.split("\\\\s+") from Pattern :

s means A whitespace character
s+ means one or many whitespaces

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM