-2

Outline how a Java program could convert a string such as “1,2,3,4,5” into an array ({1, 2, 3, 4,5})

Gorakh_sth
  • 171
  • 2
  • 3
  • 10

5 Answers5

7

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 
    }
}
george mano
  • 5,948
  • 6
  • 33
  • 43
Martin
  • 830
  • 1
  • 7
  • 24
  • It work for me thank you for your response but how does the .split(",") work ? – Gorakh_sth Mar 07 '13 at 12:49
  • 1
    Consult the Java API, it's a String method. http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29 – Martin Mar 07 '13 at 12:51
3

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) {};
}
bsiamionau
  • 8,099
  • 4
  • 46
  • 73
1

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;
}
elcuco
  • 8,948
  • 9
  • 47
  • 69
Jeevan Patil
  • 6,029
  • 3
  • 33
  • 50
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]);
TizianoPiccardi
  • 487
  • 4
  • 13
0

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"));
MMascarin
  • 468
  • 4
  • 6