0

I am trying to figure out how it works, I tried several different examples and I just don't uderstand the results I'm getting. fot example using it on string such as:

String s1 = "Hello there how are you";
String [] sa1 = s1.split("\\s");

will return array with 5 elements which are obvious and this makes sense to me. How about this:

String s1 = "Hello there how are you";
String [] sa1 = s1.split("\\S");

returns array of 17 empty strings... Could someone help me understanding it please?

Lucas
  • 3,181
  • 4
  • 26
  • 45
  • you should use `\\S+` to find anything that is separated by white spaces. [DEMO](http://regex101.com/r/vH9hS9/1) that returns 5 words as per the example. – Braj Aug 25 '14 at 18:42
  • yes, I understand quantifiers thanks for that, but my problem was slightly different. – Lucas Aug 25 '14 at 18:45

1 Answers1

5

The regex pattern \\S means not whitespace, so every letter is a separator.

You get:

  • 5 empty strings for each empty string before each letter of Hello
  • 1 single-space string " " for the space between Hello and there
  • 4 more empty strings for the empty strings in between the letters of there
  • 1 more single-space string " " for the space between there and how
  • 2 more empty strings for the empty strings in between the letters of how
  • 1 more single-space string " " for the space between how and are
  • 2 more empty strings for the empty strings in between the letters of are
  • 1 more single-space string " " for the space between how and are
  • There would be 3 more empty strings for you, but String's split method discards trailing empty strings.

Adding them all up you get your 17 elements. Most of them are empty strings, but 4 of them are not empty and consist of a single space.

rgettman
  • 176,041
  • 30
  • 275
  • 357