Home > Back-end >  java .split() method gives arrays of different lengths
java .split() method gives arrays of different lengths

Time:11-12

I am reading lines from a tsv file, and then trying to delimit them by words = array.split("\t")

words is an array that i have already initiated by String[] words = {"0", "0", "0", "0", "0", "0"} so it has a fixed length of 6. However, words[i] can have a different length of words[j]. I absolutely want words to have its length fixed to 6. Why is that happening and how do i fix this?

Tried for(int i=0; i<x; i ){ String[] words = new String[6] }

CodePudding user response:

String.split has an override you can use to limit the output. It will grab the first n number of the string and then stop.

From the documentation:

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.

  • If the limit is positive then the pattern will be applied at most limit - 1 times, the array's length will be no greater than limit, and the array's last entry will contain all input beyond the last matched delimiter.

  • If the limit is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

  • If the limit is negative then the pattern will be applied as many times as possible and the array can have any length.

Here's an example

String[] splitWithoutLimit = "Column1,Column2,Column3".split(",")

// splitWithoutLimit will contain the following values:
// { "Column1", "Column2", "Column3" }

String[] splitWithLimit = "Column1,Column2,Column3".split(",", 2)

// splitWithLimit will contain the following values:
// { "Column1", "Column2,Column3" }

CodePudding user response:

Splitting a string, taking maximum 6 values, and filling an array with the "0" string if there are too few values.

        String[] defaultWords = {"0", "0", "0", "0", "0", "0"};
        int fixedSize = defaultWords.length;
        String[] words = new String[fixedSize];

        // reading
        String str = "1\t2\t3";
        String[] tmpWords = str.split("\t");
        System.arraycopy(defaultWords, 0, words, 0, fixedSize);
        System.arraycopy(tmpWords, 0, words, 0, Math.min(fixedSize, tmpWords.length));

        System.out.println(Arrays.toString(words));

Result:

[1, 2, 3, 0, 0, 0]
  • Related