Java的indexof怎样快速找到子串

avatar
作者
猴君
阅读量:19

在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); 

广告一刻

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