java中indexof方法如何使用

38次阅读
没有评论

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

在 Java 中,indexOf方法用于查找指定字符或子字符串在字符串中第一次出现的位置。它有两种形式的使用:

  1. 查找指定字符的位置:
String str = "Hello, world!";
int index = str.indexOf('o');
System.out.println(index); // 输出 4 
  1. 查找指定子字符串的位置:
String str = "Hello, world!";
int index = str.indexOf("world");
System.out.println(index); // 输出 7 

如果要查找从指定位置开始的第一次出现的位置,可以使用带有第二个参数的 indexOf 方法:

String str = "Hello, world!";
int index = str.indexOf('o', 5); // 从索引为 5 的位置开始查找
System.out.println(index); // 输出 7 

如果要查找最后一次出现的位置,可以使用 lastIndexOf 方法:

String str = "Hello, world!";
int index = str.lastIndexOf('o');
System.out.println(index); // 输出 8 

需要注意的是,indexOf方法返回的是字符或子字符串第一次出现的索引,如果找不到指定字符或子字符串,返回 -1。

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

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