[英]How can I export numbers between spaces in a string in Java?
I want to input a String
like this "5 4 34" from keyboard. 我想从键盘输入这样的
String
“ 5 4 34”。 How can I export the numbers between spaces? 如何导出空格之间的数字? Also a want to export them into an
int[]
array, and print them on the screen. 还要将它们导出到
int[]
数组中,然后在屏幕上打印出来。
You can use String.split("\\\\s")
to split the String
to String[]
and then use Integer.parseInt()
on each element to get the number as an int
. 您可以使用
String.split("\\\\s")
将String
拆分为String[]
,然后在每个元素上使用Integer.parseInt()
以将数字作为int
来获取。
Alternatively, you can use a Scanner
, and its nextInt()
method 另外,您可以使用
Scanner
及其nextInt()
方法
Since the others have already showed you how it can be done with split()
, here is an example how to do it with Scanner
, directly from System.in
(I am assuming that what you want, because you say you read it from keyboard, of course you can use any Readable
or a String
to build your Scanner
): 由于其他人已经向您展示了如何使用
split()
完成此操作,因此这里有一个示例,如何直接从System.in
使用Scanner
进行操作(我假设您想要的是因为您说的是从键盘上读取的,当然您可以使用任何Readable
或String
来构建您的Scanner
):
Code: 码:
Scanner inputScanner = new Scanner(System.in);
Scanner scanner = new Scanner(inputScanner.nextLine());
List<Integer> list = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
Integer[] arr = list.toArray(new Integer[0]);
or if you want an int[]
and not an Integer[]
instead of the last line, use: 或者,如果您要使用
int[]
而不是Integer[]
而不是最后一行,请使用:
int[] arr = new int[list.size()];
int i = 0;
for (Integer x : list) {
arr[i++] = x;
}
To print the array just print the result of Arrays.toString()
: 要打印数组,只需打印
Arrays.toString()
的结果:
System.out.println(Arrays.toString(arr));
Add an exception handler and you're in good shape: 添加一个异常处理程序,您就可以保持良好状态:
String values = "5 4 34";
String [] tokens = values.split("\\s+");
List<Integer> numbers = new ArrayList<Integer>();
for (String number : tokens) {
numbers.add(Integer.valueOf(number);
}
Or like this: 或像这样:
String values = "5 4 34";
String [] tokens = values.split("\\s+");
int [] numbers = new int[tokens.length];
for (int i = 0; i < tokens.length; ++i) {
numbers[i] = Integer.valueOf(tokens[i]);
}
String[] stringArray = "5 4 34".split( " " );
int[] intArray = new int[ stringArray.length ];
for ( int i = 0 ; i < stringArray.length ; i++ )
{
intArray[ i ] = Integer.parseInt( stringArray[ i ] );
}
String string = "5 4 34";
String[] components = string.split(" "); // [5, 4, 34]
Without much boilerplate: 没有太多样板:
List <Integer> numbers = new ArrayList <Integer> ();
for (String number : "5 4 34";.split ("\\s+")) {
int v = Integer.parseInt (number);
System.out.println (v);
numbers.add (v);
}
Or using Scanner: 或使用扫描仪:
Scanner scanner = new Scanner ("5 4 34");
List <Integer> list = new ArrayList <Integer> ();
while (scanner.hasNextInt()) {
int v = scanner.nextInt ();
list.add (v);
System.out.println (v);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.