I have a string like "2020". When I split it with split(""). Then i checked its length. It is giving me 5 . But it should give 4. What is the reason
Asked
Active
Viewed 77 times
0
-
1[this](http://stackoverflow.com/questions/22718744/why-does-split-in-java-8-sometimes-remove-empty-strings-at-start-of-result-array) may explain – Reimeus Feb 24 '15 at 18:33
-
When I run split on the same string, I get the length you expect, 4. See https://ideone.com/QKf5Bb – Alex Feb 24 '15 at 18:33
-
I can't reproduce this. What are you trying to achieve, anyway? – Jon Skeet Feb 24 '15 at 18:36
-
The behaviour has changed in Java 8. You would get expected result there. – Rohit Jain Feb 24 '15 at 18:37
-
@Reimeus Now I understand – dasamit7 Feb 24 '15 at 18:38
-
@JonSkeet It was annoying behaviour of Java before version 8 where it was improved. Often we had to split on `(?!^)` to avoid splitting on empty space which was placed at start of the String. – Pshemo Feb 24 '15 at 18:38
-
1Interesting. I still wonder what the OP is trying to achieve that couldn't be more readably achieved in a different way. – Jon Skeet Feb 24 '15 at 18:42
-
@dasamit7 What are you trying to achieve with this code? If you want to know how many characters there is in string you can simply call `yourString.length()` method. If you want to iterate over all characters you can simply use `char[] chars = yourStirng.toCharArray()` and iterate over it, or use `yourStirng.charAt(index)`. Why do you want to create `String[]` array? – Pshemo Feb 24 '15 at 18:48
-
@Pshemo. I know that but I wanted to know why that was happening with split method. – dasamit7 Feb 25 '15 at 04:44
-
Then you probably found your answer in duplicates. If not consider reading http://stackoverflow.com/q/28486166/1393766. – Pshemo Feb 25 '15 at 04:50
-
@Pshemo I understand that now – dasamit7 Feb 25 '15 at 04:51