概述 Java 程序如何将诸如“1,2,3,4,5”之类的字符串转换为数组 ({1, 2, 3, 4,5})
问问题
15499 次
5 回答
7
来自 zvzdhk:
String[] array = "1,2,3,4,5".split(",");
然后,解析你的整数:
int[] ints = new int[array.length];
for(int i=0; i<array.length; i++)
{
try {
ints[i] = Integer.parseInt(array[i]);
} catch (NumberFormatException nfe) {
//Not an integer
}
}
于 2013-03-07T12:39:20.257 回答
3
试试这个:
String[] array = "1,2,3,4,5".split(",");
int[] result = new result[array.length];
for (int i = 0; i < array.length; i++) {
try {
result[i] = Integer.parseInt(array[i]);
} catch (NumberFormatException nfe) {};
}
于 2013-03-07T12:32:30.197 回答
1
使用 StringTokenizer 它将用逗号分割字符串,然后将这些值/标记放入整数数组中。
public static int[] getIntegers(String numbers) {
StringTokenizer st = new StringTokenizer(numbers, ",");
int[] intArr = new int[st.countTokens()];
int i = 0;
while (st.hasMoreElements()) {
intArr[i] = Integer.parseInt((String) st.nextElement());
i++;
}
return intArr;
}
于 2013-03-07T12:32:30.540 回答
0
String [] str = "1,2,3,4,5".split(",");
int arrayInt[] = new int[str.length];
for (int i = 0; i < str.length; i++)
arrayInt[i]=Integer.valueOf(str[i]);
于 2013-03-07T12:39:33.153 回答
0
使用 Guava,您可以在一行中做到这一点:
int[] array = Ints.toArray(Lists.newArrayList(Ints.stringConverter().convertAll(Splitter.on(",").split("1,2,3,4,5"))));
左右(如果你不需要数组):
Iterable<Integer> ints = Ints.stringConverter().convertAll(Splitter.on(",").split("1,2,3,4,5"));
于 2015-09-16T21:40:13.870 回答