Outline how a Java program could convert a string such as “1,2,3,4,5” into an array ({1, 2, 3, 4,5})
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]);
From zvzdhk:
String[] array = "1,2,3,4,5".split(",");
Then, parse your integers:
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
}
}
Use StringTokenizer which will split string by comma and then put those values/tokens in array of integers.
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;
}
Try this:
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) {};
}
With Guava you can do this in one line:
int[] array = Ints.toArray(Lists.newArrayList(Ints.stringConverter().convertAll(Splitter.on(",").split("1,2,3,4,5"))));
or so (if you don't require an array):
Iterable<Integer> ints = Ints.stringConverter().convertAll(Splitter.on(",").split("1,2,3,4,5"));