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

Java函数:如何查找字符串中特定字符的位置

发布时间:2023-06-15 05:20:42

在Java中,我们可以使用indexOf()方法来查找字符串中特定字符的位置。

语法如下:

public int indexOf(int ch)
public int indexOf(int ch, int fromIndex)
public int indexOf(String str)
public int indexOf(String str, int fromIndex)

其中,第一个方法查找给定字符最先出现的位置,第二个方法从指定索引开始查找给定字符最先出现的位置,第三个方法查找给定字符串的第一次出现的位置,第四个方法从指定索引开始查找给定字符串的第一次出现的位置。

示例如下:

public class Test {
    public static void main(String[] args) {
        String str = "Hello World!";
        
        // 查找字符o的位置
        int index1 = str.indexOf('o');
        System.out.println("o的位置:" + index1);
        
        // 从第3个字符开始查找字符o的位置
        int index2 = str.indexOf('o', 3);
        System.out.println("从第3个字符开始查找o的位置:" + index2);
        
        // 查找字符串World的位置
        int index3 = str.indexOf("World");
        System.out.println("World的位置:" + index3);
        
        // 从第6个字符开始查找字符串World的位置
        int index4 = str.indexOf("World", 6);
        System.out.println("从第6个字符开始查找World的位置:" + index4);
    }
}

输出结果为:

o的位置:4
从第3个字符开始查找o的位置:7
World的位置:6
从第6个字符开始查找World的位置:-1

其中,如果指定的字符或字符串不存在,则返回-1。