欢迎访问宙启技术站
智能推送

Java中如何使用indexOf函数来查询字符串中的指定字符位置?

发布时间:2023-11-03 15:46:55

在Java中,可以使用String类中的indexOf()方法来查询字符串中指定字符的位置。

indexOf()方法有两种重载形式:

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

2. int indexOf(int ch, int fromIndex):查询指定字符在字符串中从指定位置开始查找首次出现的位置。

下面是使用indexOf()函数查询字符串中指定字符位置的示例代码:

public class Main {
    public static void main(String[] args) {
        String str = "Hello, World!";

        // 查询字符 'o' 的位置
        int firstIndex = str.indexOf('o');
        System.out.println("字符 'o'       次出现的位置:" + firstIndex);

        // 从指定位置 5 开始查询字符 'o' 的位置
        int secondIndex = str.indexOf('o', 5);
        System.out.println("字符 'o' 第二次出现的位置:" + secondIndex);
    }
}

运行上述代码将输出:

字符 'o'       次出现的位置:4
字符 'o' 第二次出现的位置:8

注意,indexOf()方法返回的是指定字符在字符串中的索引位置,索引位置从0开始计数。如果指定字符不存在于字符串中,indexOf()方法将返回-1。

以上是使用indexOf()函数查询字符串中指定字符位置的方法。希望对你有所帮助!