简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM