温馨提示×

java中的indexof方法怎么用

小亿
93
2023-12-04 22:23:19
栏目: 编程语言

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来进行判断。

0