girionis
asked on
String split() method bug?
Consider the following:
String s = "#1#sdsd###2#dsfdf##";
System.out.println(s);
String sa [] = s.split("#");
for (int i=0; i<sa.length; i++)
{
System.out.println("token[ " + i + "]: " + sa[i]);
}
It only returns 7 tokens instead of (the expected?) 8 tokens. Is this a bug or am I missing something? I looked at java bug database but couldn't find anything.
Any thoughts?
Thank you.
String s = "#1#sdsd###2#dsfdf##";
System.out.println(s);
String sa [] = s.split("#");
for (int i=0; i<sa.length; i++)
{
System.out.println("token[
}
It only returns 7 tokens instead of (the expected?) 8 tokens. Is this a bug or am I missing something? I looked at java bug database but couldn't find anything.
Any thoughts?
Thank you.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
If you want the trailing empty strings :
String s = "#1#sdsd###2#dsfdf##";
System.out.println(s);
s=s+"end";
String sa [] = s.split("#");
for (int i=0; i<sa.length-1; i++)
{
System.out.println("token[ " + i + "]: " + sa[i]);
}
String s = "#1#sdsd###2#dsfdf##";
System.out.println(s);
s=s+"end";
String sa [] = s.split("#");
for (int i=0; i<sa.length-1; i++)
{
System.out.println("token[
}
ASKER
Maybe next time I should read the javadocs first.. thank you :)
>> " Trailing empty strings are therefore not included in the resulting array. "
Do you want it to be?
Do you want it to be?
Trailing empty strings are not returned. Look up the docs for java.lang.String.split(). Those last two '#'s won't return anything
"This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array. "
"This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array. "
If you DO want it to be, here's the correct RE
String sa[] = s.split("(?=#)");
String sa[] = s.split("(?=#)");
:-)
ASKER
Thank you everyone for your replies.
>If you DO want it to be, here's the correct RE
>
>String sa[] = s.split("(?=#)");
No I don't, the real problem was an IndexOutOfBoundsException and I just solved by iterating at the length - 1 of the array.
>If you DO want it to be, here's the correct RE
>
>String sa[] = s.split("(?=#)");
No I don't, the real problem was an IndexOutOfBoundsException and I just solved by iterating at the length - 1 of the array.
" Trailing empty strings are therefore not included in the resulting array. "