java 如何将一行中输入的逗号分隔的数字输入到Java中的数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10565335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get numbers separated by comma entered in a line into an array in Java
提问by miatech
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
我怎样才能将用户在一行中输入的值 eq: 1, 3, 400, 444 等...放入一个数组中。我知道在这种情况下我必须声明一个分隔符逗号“,”。有人可以帮忙吗
Thanks
谢谢
回答by Tomasz Nurkiewicz
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.
您可以在String.split()
like 中使用更简单的分隔符,","
但更复杂的分隔符"\\s*,\\s*"
还会去除逗号周围的空格。
回答by óscar López
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 numbersyou need to convert them.
现在answer
是一个数组,字符串中的数字为整数。其他答案只是拆分字符串,如果您需要实际数字,则需要转换它们。
System.out.println(Arrays.toString(answer));
> [1, 3, 400, 444]
回答by isvforall
String line = "1, 3, 400, 444";
for(String s : line.split(","))
System.out.println(s);
回答by user1112699
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.
这是正确的答案,"\\s*,\\s*" 是正则表达式,正则表达式对于字符串解析非常有用。