tags:

views:

95

answers:

2

The following Java code will print "0". I would expect that this would print "4". According to the Java API String.split "Splits this string around matches of the given regular expression". And from the linked regular expression documentation:

Predefined character classes
. Any character (may or may not match line terminators)

Therefore I would expect "Test" to be split on each character. I am clearly misunderstanding something.

System.out.println("Test".split(".").length); //0

+5  A: 

You're right: it is split on each character. However, the "split" character is not returned by this function, hence the resulting 0.

The important part in the javadoc: "Trailing empty strings are therefore not included in the resulting array. "

I think you want "Test".split(".", -1).length(), but this will return 5 and not 4 (there are 5 ''spaces'': one before T, one between T and e, others for e-s, s-t, and the last one after the final t.)

Jerome
Thanks. I see whats going on now.
Jon
+1  A: 

Everything is ok. "Test" is split on each character, and so between them there is no character. If you want iterate your string over each character you can use charAt and length methods.

kogut