• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3068
  • Last Modified:

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.
0
girionis
Asked:
girionis
  • 4
  • 2
  • 2
  • +1
1 Solution
 
WebstormCommented:
From API javadoc:
  " Trailing empty strings are therefore not included in the resulting array. "


0
 
WebstormCommented:
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]);
}
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
girionisAuthor Commented:
Maybe next time I should read the javadocs first.. thank you :)
0
 
CEHJCommented:
>> " Trailing empty strings are therefore not included in the resulting array. "

Do you want it to be?
0
 
Andy_NeodyniumCommented:
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. "
0
 
CEHJCommented:
If you DO want it to be, here's the correct RE

String sa[] = s.split("(?=#)");
0
 
WebstormCommented:
:-)
0
 
girionisAuthor 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.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 4
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now