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

岁酱吖の 提交于 2019-12-24 10:47:11

问题


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


回答1:


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.




回答2:


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]



回答3:


You want to use split:

userInput.split(",");



回答4:


String line = "1, 3, 400, 444";
for(String s : line.split(","))
   System.out.println(s);



回答5:


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.



来源:https://stackoverflow.com/questions/10565335/how-to-get-numbers-separated-by-comma-entered-in-a-line-into-an-array-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!