• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

Question about split()

 
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Would anyone be able to explain me why in this code:

String s = "aaaaaaaaabbb";
String[] arr = s.split("a{3}");
System.out.println(arr.length + "");

The output is 4, rather than 3

Thanks
Katrin
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The split() method splits the string around occurrences of the regular expression that you pass to it. Your regular expression "a{3}" matches the character a, tree times (so: "aaa"). Did you look at the elements in the returned array? It contains: three times the empty string, and the fourth element contains "bbb".

Note that split() removes the matches from the input string and returns the text between the matches. So the "aaa"'s are removed, and the text around those "aaa"'s is returned. Since there are no characters between the nine "a"'s, you'll get three times the empty string first, and then the final "bbb".

Lookup the API documentation of the String.split() method for an exact description of what the method does.
 
Katrin Perry
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you Jesper.

In general I understand how it works, I suppose I got a bit confused about the first empty String in the returned array. I understand about where the other 2 would come from + the "bb"

Katrin
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Howdy!

I modified Katrin's code a bit, original in bold:


The first three are the three null-strings after the triple-a.
The split splits just after the positions marked by the X.


Hope it helps,

Yours,
Bu.

edit: the last C is just one too many...
[ September 13, 2007: Message edited by: Burkhard Hassel ]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic