Java的indexof怎样快速找到子串

   2024-10-07 8220
核心提示:在Java中,可以使用String类的indexOf方法来快速找到子串在字符串中的位置。该方法的语法如下:public int indexOf(String str)

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

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号