温馨提示×

java中index函数的用法是什么

小亿
88
2024-03-02 14:43:40
栏目: 编程语言

在 Java 中,indexOf() 函数用于查找指定字符串或字符在字符串中第一次出现的位置索引。以下是 indexOf() 函数的常见用法:

  1. 使用 indexOf(String str) 方法:此方法用于查找一个特定字符串在另一个字符串中第一次出现的位置。如果未找到匹配的子字符串,则返回 -1。示例:

    String str = "Hello, World!";
    int index = str.indexOf("World");
    System.out.println(index); // 输出:7
    
  2. 使用 indexOf(int ch) 方法:此方法用于查找指定字符在字符串中第一次出现的位置。示例:

    String str = "Hello, World!";
    int index = str.indexOf('o');
    System.out.println(index); // 输出:4
    
  3. 使用 indexOf(String str, int fromIndex) 方法:该方法允许从指定的索引位置开始搜索指定的子字符串。示例:

    String str = "Hello, World!";
    int index = str.indexOf("l", 3);
    System.out.println(index); // 输出:3
    

通过上述方法,你可以利用 indexOf() 函数在 Java 中查找指定字符串或字符在另一个字符串中的位置索引。

0