String.indexOf(int x)和String.indexOf(String)之间的区别

-8 java string

类中有两种方法String看起来像是做同样的事情:

  • indexOf(int)
  • indexOf(String)

有人可以解释这两个功能之间的区别是什么?

Luc*_*cci 5

  • String.indexOf(int):Returns the index within this string of the first occurrence of the specified character.
  • String.indexOf(String):Returns the index within this string of the first occurrence of the specified substring.

例:

String test = "aaabbbaaabbb";
test.indexOf('a') return 0 (first 'a' in string)
test.indexOf('b') return 3 (first 'a' in string)
test.indexOf("aaa") return 0 (first "aaa" in string)
test.indexOf("bbb") return 3 (first "bbb" in string)
test.indexOf("sajx") return -1 (not found)
Run Code Online (Sandbox Code Playgroud)