Java String.indexOf and empty Strings

后端 未结 5 851
借酒劲吻你
借酒劲吻你 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.

提交回复
热议问题