Java String indexOf() 方法
示例
搜索字符串中第一次出现的“planet”
String myStr = "Hello planet earth, you are a great planet.";
System.out.println(myStr.indexOf("planet"));
定义和用法
indexOf()
方法返回指定字符在字符串中第一次出现的位置。
提示: 使用 lastIndexOf 方法返回指定字符在字符串中**最后**一次出现的位置。
语法
以下之一
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 |
---|
更多示例
示例
在一个字符串中查找字母“e”的第一次出现,从位置 5 开始搜索
public class Main {
public static void main(String[] args) {
String myStr = "Hello planet earth, you are a great planet.";
System.out.println(myStr.indexOf("e", 5));
}
}
❮ String Methods