indexOf()方法返回字符串中首次出现的指定字符的索引位置。
提示:使用lastIndexOf方法返回字符串中最后一次出现指定字符的位置。
有4个indexOf()方法:
public int indexOf(String str) public int indexOf(String str, int fromIndex) public int indexOf(int char) public int indexOf(int char, int fromIndex)
| 参数 | 描述 |
| str | String值,表示要搜索的字符串 |
| fromIndex | int值,表示从中开始搜索的索引位置 |
| char | int值,表示单个字符,例如,’A’或Unicode值 |
| 返回值: | int值,表示字符串中字符首次出现的索引,如果从未出现,则为-1 |
例如:
在字符串中找到字母”java”的第一个匹配项,从位置10开始搜索:
public class Main {
public static void main(String[] args) {
String myStr = "c java python is wx and www.wx1986.com";
System.out.println(myStr.indexOf("java", 10));
}
}