how to get numbers separated by comma entered in a

2019-08-07 02:12发布

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

Thanks

5条回答
冷血范
2楼-- · 2019-08-07 02:30
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.

查看更多
聊天终结者
3楼-- · 2019-08-07 02:32
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.

查看更多
forever°为你锁心
4楼-- · 2019-08-07 02:34

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]
查看更多
疯言疯语
5楼-- · 2019-08-07 02:43

You want to use split:

userInput.split(",");
查看更多
你好瞎i
6楼-- · 2019-08-07 02:46
String line = "1, 3, 400, 444";
for(String s : line.split(","))
   System.out.println(s);
查看更多
登录 后发表回答