一、概述
indexOf方法是Java中常用的一种字符串查找方法,用于查找指定字符或字符串在字符串中第一次出现的位置。
该方法位于java.lang.String类中,可以根据需要传入一个字符或字符串参数。如果该字符或字符串出现在原字符串中,则返回它在原字符串中的起始索引(从0开始计算),如果没有找到则返回-1。
二、语法
public int indexOf(int ch) public int indexOf(int ch, int fromIndex) public int indexOf(String str) public int indexOf(String str, int fromIndex)
三、用法示例
1、查找字符
String str = "hello world"; int index = str.indexOf('o'); System.out.println(index); //输出结果为4
上述代码表示在字符串”hello world”中查找第一个’o’,返回其在原字符串中位置的索引值。因为’o’出现在字符串的第5个位置,而Java中索引从0开始计算,所以最终结果为4。
2、查找字符串
String str = "hello world"; int index = str.indexOf("world"); System.out.println(index); //输出结果为6
此处通过传入一个字符串参数来查找”world”在原字符串中首次出现的位置。因为”world”出现在字符串的第7个位置,所以最终结果为6。
3、指定起始位置查找
String str = "hello world"; int index = str.indexOf('o', 5); System.out.println(index); //输出结果为7
通过在indexOf方法中传入第二个参数来指定查找的起始位置。上述代码表示从字符串的第6个位置开始查找第一个’o’,找到后返回其在原字符串中位置的索引值。因为’o’出现在字符串的第8个位置,所以最终结果为7。
4、未找到指定字符或字符串
String str = "hello world"; int index = str.indexOf('z'); System.out.println(index); //输出结果为-1
如果指定的字符或字符串没有在原字符串中出现,则indexOf方法返回-1。
四、总结
indexOf方法是Java常用的字符串查找方法,可以很方便地查找指定字符或字符串在字符串中的位置。合理使用该方法,可以提高代码开发效率。
需要注意的是,在使用indexOf方法时,要考虑字符或字符串在原字符串中可能出现的位置,以及是否需要查找多次等问题,以免引起不必要的性能问题。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/294147.html