Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
 
What have you tried? –  Evan Knowles Mar 7 '13 at 12:32
 
Check this link: answers.yahoo.com/question/index?qid=20090824115249AAXkde1 –  Sarang Mar 7 '13 at 12:38
add comment

4 Answers

up vote 0 down vote accepted

From zvzdhk:

String[] array = "1,2,3,4,5".split(",");

Then, parse your integers:

int[] ints = new int[arrays.length];
for(int i=0; i<array.length; i++)
{
    try{
        ints[i] = Integer.parseInt(array[i]);
    }
    catch(NumberFormatException nfe){
        //Not an integer, do some
    }
}
share|improve this answer
 
It work for me thank you for your response but how does the .split(",") work ? –  Gorakh_sth Mar 7 '13 at 12:49
1  
Consult the Java API, it's a String method. docs.oracle.com/javase/6/docs/api/java/lang/… –  Ph4g3 Mar 7 '13 at 12:51
add comment

Use StringTokenizer which will split string by comma and then put those values/tokens in array of integers.

StringTokenizer st = new StringTokenizer("1,2,3,4,5", ",");

int[] intArr = new int[st.countTokens()];
int i = 0;
while (st.hasMoreElements()) {
    intArr[i] = Integer.parstInt(st.nextElement());
    i++
}
share|improve this answer
 
thank you so much –  Gorakh_sth Mar 7 '13 at 12:50
add comment

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) {};
}
share|improve this answer
 
He need an Integer Array. –  Kugathasan Abimaran Mar 7 '13 at 12:33
 
thank you for your response .. –  Gorakh_sth Mar 7 '13 at 12:49
 
@Gorakh_sth you're welcome. –  zvdh Mar 7 '13 at 19:20
add comment
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]);
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.