-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})

1

5 Answers 5

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 
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

It work for me thank you for your response but how does the .split(",") work ?
Consult the Java API, it's a String method. docs.oracle.com/javase/6/docs/api/java/lang/…
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) {};
}

Comments

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;
}

Comments

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]);

Comments

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"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.