简体   繁体   中英

Java String IndexOf behaviour for empty string

对于字符串, String str = "abc" str.indexOf("a")str.indexOf("")返回0。此行为有效吗?

If only there was some place where they document behaviour of methods.

indexOf(string)

Returns the index within this string of the first occurrence of the specified substring. The returned index is the smallest value k for which:

this.startsWith(str, k)

startsWith(string)

true if the character sequence represented by the argument is a prefix of the character sequence represented by this string; false otherwise. Note also that true will be returned if the argument is an empty string or is equal to this String object as determined by the equals(Object) method.

Yes. The conceptual reason is pretty similar as adding 0 in math. So ""+"a"+"bc" = "abc" = ""+"a"+"b"+""+"c" .

The return value of String.indexof("") is 0 , or the starting index, when you pass in an empty string because the empty string "" is indeed located there. Think of "abc" as "" + "abc" .

Otherwise, please refer to this documentation:

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int)

indexOf "returns:the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur."

Therefore, str.indexOf("a") returns 0.

Think of it as

"" +"abc"="abc"

basically

"abc" is ""+"abc"

实际上,任何不为null的字符串中都存在一个空字符串。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM