简体   繁体   中英

How to get numbers separated by comma entered in a line into an array in Java

How could I get values entered in a single line by the user eq: 1, 3, 400, 444, etc.. into an array. I know I must declare a separator in this case the comma ",". Could someone help?

String input = "1, 3, 400, 444";
String[] numbers = input.split("\\s*,\\s*");

You can use much simpler separator in String.split() like "," but the more complex "\\s*,\\s*" additionally strips whitespaces around comma.

你想使用split

userInput.split(",");

Try this:

String line = "1, 3, 400, 444";

String[] numbers = line.split(",\\s+");
int[] answer = new int[numbers.length];

for (int i = 0; i < numbers.length; i++)
    answer[i] = Integer.parseInt(numbers[i]);

Now answer is an array with the numbers in the string as integers. The other answers just split the string, if you need actual numbers you need to convert them.

System.out.println(Arrays.toString(answer));
> [1, 3, 400, 444]
String line = "1, 3, 400, 444";
for(String s : line.split(","))
   System.out.println(s);
String input = "1, 3, 400, 444";
String[] numbers = input.split("\\s*,\\s*");

It's the right answer, "\\s*,\\s*" is a regular expression, regex is very useful for the string parsing.

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