温馨提示×

java中indexof的用法是什么

小亿
93
2023-12-28 01:26:22
栏目: 编程语言

在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()方法。

0