java中indexof的用法是什么

avatar
作者
筋斗云
阅读量:3

在Java中,indexOf()是String类的一个方法,用于在字符串中查找指定字符或子字符串的第一个匹配项的索引位置。它有两种使用方式:

  1. indexOf(char ch):查找指定字符ch在字符串中第一次出现的索引位置。如果找到匹配项,则返回其索引值;如果未找到匹配项,则返回-1。 示例:
String str = "Hello World"; int index = str.indexOf('o'); System.out.println(index);  // 输出结果为 4 
  1. indexOf(String str):查找指定字符串str在字符串中第一次出现的索引位置。如果找到匹配项,则返回其索引值;如果未找到匹配项,则返回-1。 示例:
String str = "Hello World"; int index = str.indexOf("lo"); System.out.println(index);  // 输出结果为 3 

另外,indexOf()方法还可以通过指定一个起始索引来进行搜索。例如,可以使用indexOf(String str, int fromIndex)来指定从字符串的某个位置开始搜索匹配项的索引位置。

String str = "Hello World"; int index = str.indexOf('o', 5);  // 从索引5开始搜索 System.out.println(index);  // 输出结果为 7 

需要注意的是,indexOf()方法是区分大小写的,如果要进行大小写不敏感的搜索,可以使用equalsIgnoreCase()方法。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!