regex - How to avoid Blank space insertion at the beginning of the String in Java while using Split() function -
here code snippet.
public static void main(string...strings){ string s="google"; string[] s1=s.split(""); system.out.println(s1[0]); system.out.println(s1.length); }
i'm trying split string s around each character. problem while splitting blank space getting introduced @ begining of splitted array. giving me output length 7 instead of 6. , since can't have trailing spaces split here getting passed split("", 0)
, has @ beginning test printed s1[0]
, giving blank space indeed.
my question how avoid such problem. need use split.
what happening here.?
the method string.split()
behaves differently in java 7 (used ideone) , java 8 (probably used of commenters , answerers). in java 8 javadoc documentation string.split()
, following written:
when there positive-width match @ beginning of string empty leading substring included @ beginning of resulting array. zero-width match @ beginning never produces such empty leading substring.
so, according java 8, "google".split("")
equal ["g","o","o","g","l","e"]
.
this remark not present in java 7 documentation, , indeed, in java 7 seems "google".split("")
equal ["", "g","o","o","g","l","e"]
.
(both in java 7 , in java 8 empty strings @ end of array removed.)
the best solution seems to add code ignore first string if empty. (note split("\\b")
solution suggested in answer yields unexpected results when input consists of more 1 word.)
Comments
Post a Comment