java中的indexOf()方法怎么使用

23次阅读
没有评论

共计 1105 个字符,预计需要花费 3 分钟才能阅读完成。

在 Java 中,indexOf()方法用于查找指定字符或字符串在字符串中第一次出现的位置。它的语法如下:

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. 第一个重载方法 indexOf(int ch) 接受一个字符作为参数,并返回该字符在字符串中第一次出现的位置。如果字符不存在于字符串中,则返回 -1。
String str = "Hello World";
int index = str.indexOf('o');
System.out.println(index);  // 输出:4
  1. 第二个重载方法 indexOf(int ch, int fromIndex) 接受两个参数,第一个参数是要查找的字符,第二个参数是搜索的起始位置。它从起始位置向后搜索字符串,并返回字符第一次出现的位置。如果字符不存在于指定的起始位置后的子字符串中,则返回 -1。
String str = "Hello World";
int index = str.indexOf('o', 5);
System.out.println(index);  // 输出:7
  1. 第三个重载方法 indexOf(String str) 接受一个字符串作为参数,并返回该字符串在原字符串中第一次出现的位置。如果字符串不存在于原字符串中,则返回 -1。
String str = "Hello World";
int index = str.indexOf("World");
System.out.println(index);  // 输出:6
  1. 第四个重载方法 indexOf(String str, int fromIndex) 接受两个参数,第一个参数是要查找的字符串,第二个参数是搜索的起始位置。它从起始位置向后搜索字符串,并返回字符串第一次出现的位置。如果字符串不存在于指定的起始位置后的子字符串中,则返回 -1。
String str = "Hello World";
int index = str.indexOf("World", 4);
System.out.println(index);  // 输出:-1

请注意,indexOf()方法返回的是找到的字符或字符串的索引值,索引从 0 开始。如果要查找字符或字符串最后一次出现的位置,可以使用 lastIndexOf()方法。

String str = "Hello World";
int index = str.lastIndexOf('o');
System.out.println(index);  // 输出:7

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-20发表,共计1105字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)