0

Trying to figure this out and couldn't find the answer anywhere. If i have a string and i split it in the spaces, like:

string[] arr_str = sentence.split(' ');

I will get an array with string. Now, if i enter double spaces in the sentence i will get arr_str cells with empty strings ("").

My question is why? why not with spaces???

When i do the check for the arr_str why do i need to check for empty string and not for null or spaces?

why only empty strings works?

1
  • Wait till Jon Skeet watch this ,he will explain it vulnerable. Commented Nov 14, 2011 at 21:22

4 Answers 4

1

It performs a split on one character, not including that character. As a result you're getting substrings that are between the split characters, in which case they're just empty strings.

You can, however, filter out empty strings if you want, by passing the appropriate enum the the method.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, What did you mean between those chars? isn't the split doing a left and right for the char[] in the split method? from what you said someone can understand that the function is looking for two spaces to split between....???
Sorry, by "those characters" I was referring to split characters. Answer edited.
Thanks, I didn't know the last part of your answer, that is very interesting, i just checked for cells with empty strings, but this is much more elegant... thank you :-)
1

You are splitting a string, which will results in strings.

if you split a double space, both spaces are removed but the emtpy string remains and that is your result.

Comments

1

If you enter double spaces, the split by space gets the string between two consecutive spaces which is an empty string. Like space space = space empty_string space.

Comments

1

And empty string is a String with no Value ,and a null string is a String with no Reference(is not yet initiated). A null string does not take space into memory ,but an empty string does allocate space into memory.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.