Abaab
Abaab

Reputation: 571

Java split() a String made out of the String you are splitting with?

When I compile and run this code:

class StringTest {
    public static void main(String[] args) {
        System.out.println("Begin Test");

        String letters = "AAAAAAA"
        String[] broken = letters.split("A");
        for(int i = 0; i < broken.length; i++)
            System.out.println("Item " + i + ": " + broken[i]);

        System.out.println("End Test");
    }
}

The output to the console is:

Begin Test
End Test

Can anyone explain why split() works like this? I saw some other questions sort of like this on here, but didn't fully understand why there is no output when splitting a string made entirely out of the character that you are using for regex. Why does java handle Strings this way?

Upvotes: 3

Views: 193

Answers (3)

Louis Wasserman
Louis Wasserman

Reputation: 198033

String.split discards trailing empty strings. For example, "foo,bar,,".split(",") gets split into {"foo", "bar"}. What you're seeing is a string that consists entirely of the separator, so all the empty splits are "trailing" and get discarded.

You could probably get all those empty strings if you used letters.split("A", -1). Alternately, Guava's Splitter doesn't do things like that unless you ask for it: Splitter.on('A').split(letters).

Upvotes: 12

Bohemian
Bohemian

Reputation: 424993

Since every character in your input is a delimiter, every string found is blank. By default, every trailing blank found is ignored, hence what you're seeing.

However, split() comes in two flavours. There is a second version of the split() method that accepts another int parameter limit, which controls the number of times the match is to be applied, but also the behaviour of ignoring trailing blanks.

If the limit parameter is negative, trailing blanks are preserved.

If you executed this code:

String letters = "AAAAAAA";
String[] broken = letters.split("A", -1); // note the -1
System.out.println(Arrays.toString(broken));

You get this output:

{"", "", "", "", "", "", ""}

See the javadoc for more, including examples of how various limit values affect behaviour.

Upvotes: 1

anubhava
anubhava

Reputation: 785068

It is because "A" is used as delimiter in split method and since you don't have any other text in your string other than delimiter "A" therefore after split you are left with nothing (empty string is not returned in the resulting array).

Upvotes: 1

Related Questions