We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

String split() method bug?

girionis
girionis asked
on
Medium Priority
3,081 Views
Last Modified: 2007-12-19
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.
Comment
Watch Question

Top Expert 2004

Commented:
From API javadoc:
  " Trailing empty strings are therefore not included in the resulting array. "


Top Expert 2004
Commented:
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview
Top Expert 2004

Commented:
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]);
}
CERTIFIED EXPERT
Distinguished Expert 2019

Author

Commented:
Maybe next time I should read the javadocs first.. thank you :)
CERTIFIED EXPERT
Top Expert 2016

Commented:
>> " Trailing empty strings are therefore not included in the resulting array. "

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. "
CERTIFIED EXPERT
Top Expert 2016

Commented:
If you DO want it to be, here's the correct RE

String sa[] = s.split("(?=#)");
Top Expert 2004

Commented:
:-)
CERTIFIED EXPERT
Distinguished Expert 2019

Author

Commented:
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.
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a free trial preview!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.