Java String.indexOf and empty Strings

后端 未结 5 820
借酒劲吻你
借酒劲吻你 2020-11-27 06:26

I\'m curious why the String.indexOf is returning a 0 (instead of -1) when asking for the index of an empty string within a string.

The Javadocs only say this method

相关标签:
5条回答
  • 2020-11-27 06:55

    By using the expression "", you are actually referring to a null string. A null string is an ethereal tag placed on something that exists only to show that there is a lack of anything at this location.

    So, by saying "".indexOf( "" ), you are really asking the interpreter:

    Where does a string value of null exist in my null string?

    It returns a zero, since the null is at the beginning of the non-existent null string.

    To add anything to the string would now make it a non-null string... null can be thought of as the absence of everything, even nothing.

    0 讨论(0)
  • 2020-11-27 06:58

    Well, if it helps, you can think of "FOO" as "" + "FOO".

    0 讨论(0)
  • 2020-11-27 07:15

    int number_of_empty_strings_in_string_named_text = text.length() + 1

    All characters are separated by an empty String. Additionally empty String is present at the beginning and at the end.

    0 讨论(0)
  • 2020-11-27 07:17

    The empty string is everywhere, and nowhere. It is within all strings at all times, permeating the essence of their being, yet as you seek it you shall never catch a glimpse.

    How many empty strings can you fit at the beginning of a string? Mu

    The student said to the teacher,

    Teacher, I believe that I have found the nature of the empty string. The empty string is like a particle of dust, and it floats freely through a string as dust floats freely through the room, glistening in a beam of sunlight.

    The teacher responded to the student,

    Hmm. A fine notion. Now tell me, where is the dust, and where is the sunlight?

    The teacher struck the student with a strap and instructed him to continue his meditation.

    0 讨论(0)
  • 2020-11-27 07:18

    Using an algebraic approach, "" is the neutral element of string concatenation: x + "" == x and "" + x == x (although + is non commutative here).

    Then it must also be:

    x.indexOf ( y ) == i and i != -1 
    <==> x.substring ( 0, i ) + y + x.substring ( i + y.length () ) == x
    

    when y = "", this holds if i == 0 and x.substring ( 0, 0 ) == "". I didn't design Java, but I guess mathematicians participated in it...

    0 讨论(0)
提交回复
热议问题