Michael Michael - 1 month ago 7
Java Question

How to split multiple tab delimited lines in Java if they all have a different number of columns?

I have a text file which is tab delimited, but there are a different number of columns on each line. Here is an example:

1 : 2 16 17 24 31 34 40 41 45 47 48
2 : 1 3 4 5 6 7 8 13 18 20 22 28 33 35 37 38 42 44 46 49
3 : 2 10 12 16 17 19 24 25 29 31 34 40 41 45


I want to use the split function, like I did here for a different assignment:

String[] words = line.split("\t");
col1 = Integer.parseInt(words[0]);
col2 = Integer.parseInt(words[1]);
col3 = Integer.parseInt(words[2]);
col4 = Integer.parseInt(words[3]);


This puts each column from a line into a different variable. I want to do the same but I'm not sure how to do this with a varying number of columns.

Answer

As said in the comments, you're quite good with what you've done. If you really want to have your Integer values stored somehow, you could simply use an Integer array, and fill it with a loop like this:

String[] words = line.split("\t");
int[] numbers = new int[words.length];
for (int i = 0; i < words.length; i++)
{
    numbers[i] = Integer.parseInt(words[i]);
}

That whole thing being inside the loop you use to iterate your lines.

I don't think you need anything more complex than an array.

Comments