Java String.indexOf and empty Strings

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

提交回复
热议问题