Prabhat Yadav
Prabhat Yadav

Reputation: 1331

How to convert the numeric comma separated string into int array

    //convert the comma separated numeric string into the  array of int. 
    public class HelloWorld
    {
      public static void main(String[] args)
      {
       // line is the input  which have the comma separated number
        String line = "1,2,3,1,2,2,1,2,3,";
       // 1 > split   
         String[] inputNumber =  line.split(",");
       // 1.1 > declare int array
         int number []= new int[10];
       // 2 > convert the String into  int  and save it in int array.
         for(int i=0; i<inputNumber.length;i++){
               number[i]=Integer.parseInt(inputNumber[i]);
         }
    }
}

Is it their any better solution of doing it. please suggest or it is the only best solution of doing it.

My main aim of this question is to find the best solution.

Upvotes: 1

Views: 15699

Answers (3)

shmosel
shmosel

Reputation: 50716

Since you don't like Java 8, here is the Best™ solution using some Guava utilities:

int[] numbers = Ints.toArray(
        Lists.transform(
                Splitter.on(',')
                        .omitEmptyStrings()
                        .splitToList("1,2,3,1,2,2,1,2,3,"),
                Ints.stringConverter()));

Upvotes: 1

MartinS
MartinS

Reputation: 2790

Java 8 streams offer a nice and clean solution:

String line = "1,2,3,1,2,2,1,2,3,";
int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();

Edit: Since you asked for Java 7 - what you do is already pretty good, I changed just one detail. You should initialize the array with inputNumber.length so your code does not break if the input String changes.

Edit2: I also changed the naming a bit to make the code clearer.

String line = "1,2,3,1,2,2,1,2,3,";
String[] tokens = line.split(",");
int[] numbers = new int[tokens.length];
for (int i = 0; i < tokens.length; i++) {
    numbers[i] = Integer.parseInt(tokens[i]);
}

Upvotes: 16

user3437460
user3437460

Reputation: 17454

By doing it in Java 7, you can get the String array first, then convert it to int array:

String[] tokens = line.split(",");
int[] nums = new int[tokens.length];

for(int x=0; x<tokens.length; x++)
    nums[x] = Integer.parseInt(tokens[x]);

Upvotes: 2

Related Questions