温馨提示×

Java的indexof怎样快速找到子串

小樊
82
2024-07-11 21:15:29
栏目: 编程语言

在Java中,可以使用String类的indexOf方法来快速找到子串在字符串中的位置。该方法的语法如下:

public int indexOf(String str)

其中,参数str是要查找的子串。该方法会返回子串在字符串中第一次出现的位置,如果未找到则返回-1。

如果要查找子串在字符串中第N次出现的位置,可以使用indexOf方法的另一个重载形式:

public int indexOf(String str, int fromIndex)

其中,参数str是要查找的子串,参数fromIndex是起始查找位置。该方法会返回子串在字符串中从fromIndex开始第一次出现的位置,如果未找到则返回-1。

示例:

String str = "Hello world, hello Java!";
String subStr = "hello";

int firstIndex = str.indexOf(subStr);
System.out.println("First occurrence of 'hello' is at index: " + firstIndex);

int secondIndex = str.indexOf(subStr, firstIndex + 1);
System.out.println("Second occurrence of 'hello' is at index: " + secondIndex);

0