Regular line-breaking of Java strings does not work properly

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

Predefined Character Classes
. Any character (may not match string terminators)

Therefore, I would expect the "Test" to be divided into each character. I am clearly misunderstanding something.

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

+4
source share
3 answers

You are right: it is divided into each character. However, the split symbol is not returned by this function, so the resulting value is 0.

The important part of javadoc: "So empty lines are not included in the resulting array."

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

+6
source

You should use two backslashes, and it should work fine: Here is an example:

 String[] parts = string.split("\\.",-1); 
+2
source

Everything is fine. A "test" is broken down into each character, so there is no character between them. If you want to iterate a string over each character, you can use the charAt and length methods.

+1
source

All Articles