在Java中,String类的indexOf()方法用于查找指定字符或子字符串在字符串中的第一次出现的位置。

方法声明如下: public int indexOf(int ch) public int indexOf(int ch, int fromIndex) public int indexOf(String str) public int indexOf(String str, int fromIndex)

参数说明:

  • ch:要查找的字符
  • fromIndex:开始查找的索引位置
  • str:要查找的子字符串

返回值:

  • 如果找到指定字符或子字符串,则返回它第一次出现的索引位置;如果未找到,则返回-1。

示例:

String str = "Hello, World!";
int index1 = str.indexOf('o');
int index2 = str.indexOf("World");
System.out.println(index1);  // 输出:4
System.out.println(index2);  // 输出:7

在上面的示例中,indexOf('o')方法返回字符'o'在字符串中第一次出现的索引位置,即4;indexOf("World")方法返回子字符串"World"在字符串中第一次出现的索引位置,即7

java中String 的 indexOf方法

原文地址: https://www.cveoy.top/t/topic/hXy8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录