概述Java程序如何将字符串(如“1,2,3,4,5”)转换为数组 ({1,2,3,4,5})
答案 0 :(得分:6)
来自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
}
}
答案 1 :(得分:2)
试试这个:
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) {};
}
答案 2 :(得分: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;
}
答案 3 :(得分: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]);
答案 4 :(得分:0)
使用番石榴,您可以在一行中执行此操作:
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"));