• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

SCJP6 study - regex string.split - strange results, can anyone explain please?

 
Nigel Shrin
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
eg based on a whizlabs q:



The length of s is: 5

0
1 12
2
3
4 2

I was expecting even numbers of 1's ie 11 to disappear, so I would have 122 remaining.
It has removed 6 pairs of 11. How do you account for the way it is storing nulls?
>
 
Henry Wong
author
Marshal
Pie
Posts: 21024
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Start with the original string...

"111211111121111"


Do a regex find to get the delimiters...

"11 12 11 11 11 2 11 11"


Add "X" to show the blank tokens...

"X 11 12 11 X 11 X 11 2 11 X 11 X "


Remove the trailing blanks, because you used the version of split() that removes them...

"X 11 12 11 X 11 X 11 2"


So, you get a final result of 5 tokens, which are blank, 12, blank, blank, and 2.

Henry
 
Ninad Kulkarni
Ranch Hand
Posts: 802
Hibernate Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Henry
Great explaination.
 
Nigel Shrin
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hi Henry, I really appreciate the reply, the penny has dropped!

I've created a more complex example and managed to predict the result.

Cheers!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic