假设我有这个字符串
String myString=" 102 3 4 93 3";
我需要能够访问字符串中的每个整数,但分隔每个整数的空格字符数量不可预测。我希望得到这样的结果
stuff[0]=102
stuff[1]=3
stuff[2]=4
stuff[3]=93
stuff[4]=3
最佳答案
首先使用trim()
删除尾随和前导空格。然后你可以使用split(regex)
:
String[] parts = myString.trim().split("\\s+");
这里我们使用:
\\s : Match any whitespace character
+ : Repeat one or more times
如果您想要 int
元素,可以使用 Integer.parseInt()
方法:
int n = Integer.parseInt(parts[0]);
关于java - 如何分解字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22597006/