java中的indexof方法怎么用

36次阅读
没有评论

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

Java 中的 indexOf 方法用于查找指定字符或子字符串在字符串中第一次出现的位置。

它的使用方法如下:

  1. indexOf(int ch):查找指定字符 ch 在字符串中第一次出现的位置。

    String str = "Hello World";
    int index = str.indexOf('o');
    System.out.println(index); // 输出 3 
    
  2. indexOf(int ch, int fromIndex):从指定索引 fromIndex 开始,查找指定字符 ch 在字符串中第一次出现的位置。

    String str = "Hello World";
    int index = str.indexOf('o', 5);
    System.out.println(index); // 输出 7 
    
  3. indexOf(String str):查找指定子字符串 str 在字符串中第一次出现的位置。

    String str = "Hello World";
    int index = str.indexOf("lo");
    System.out.println(index); // 输出 3 
    
  4. indexOf(String str, int fromIndex):从指定索引 fromIndex 开始,查找指定子字符串 str 在字符串中第一次出现的位置。

    String str = "Hello World";
    int index = str.indexOf("lo", 5);
    System.out.println(index); // 输出 -1,表示未找到 
    

需要注意的是,如果未找到指定字符或子字符串,indexOf 方法会返回 -1。如果要判断字符串中是否包含指定字符或子字符串,可以根据返回值是否为 - 1 来进行判断。

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

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