4

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

1
  • I hope this is just for curiosity's sake, because there are easier ways to find the length of a string... ;) Commented Dec 29, 2009 at 14:26

3 Answers 3

6

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I see whats going on now.
2

You have to use two backslashes and it should work fine: Here is example:

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.