从String中获取多个Integer值?

tuc*_*sss -3 java arrays string int

[这不是关于转换StringInteger]

我需要String通过控制台命令获取一些数字.

例如 :

String str = "234 432 22 66 8 44 7 4 3 333";
Run Code Online (Sandbox Code Playgroud)

如何获取每个Integer值并将它们放入数组中?数字的顺序并不重要,因为它String可能是:

String str = "34 434343 222";
Run Code Online (Sandbox Code Playgroud)

要么

String str = " 1 2 3 4 5 6 7";
Run Code Online (Sandbox Code Playgroud)

另外,如何在这两种情况下获得数字(带有一个或多个空格字符):

String str = "2 2 44 566";
Run Code Online (Sandbox Code Playgroud)

 String str = "2121     23  44 55 6   58";
Run Code Online (Sandbox Code Playgroud)

Fed*_*zza 6

如果要捕获由空格分隔的数字,则可以执行以下操作:

String str = "234 432 22 66 8 44 7 4 3 333";

String[] strArr = str.split("\\s+");
// strArr => ["234", "432", "22", "66", "8", "44", "7", "4", "3", "333"]
Run Code Online (Sandbox Code Playgroud)

更新:正如Evan LaHurd在他的评论中指出的那样,你可以处理数组值,如果你想将字符串转换为整数,你可以使用:

int n = Integer.parseInt("1234");
// or
Integer x = Integer.valueOf("1234");
Run Code Online (Sandbox Code Playgroud)

IDEOne示例

  • 然后,如果你想使用`Integer`对象,你可以在数组中的每个`String`上使用`Integer.parseInt(String s)`. (2认同)