Java indexof在字符串中怎么用

1101
2024/10/10 0:31:26
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中,indexOf()是String类的一个方法,用于查找指定字符或子字符串在字符串中首次出现的位置。如果找不到该字符或子字符串,则返回-1。

以下是使用indexOf()方法在字符串中查找字符或子字符串的示例:

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

        int index1 = str.indexOf(ch);
        int index2 = str.indexOf(sub);

        System.out.println("The index of '" + ch + "' in the string is: " + index1);
        System.out.println("The index of \"" + sub + "\" in the string is: " + index2);
    }
}

在这个例子中,我们首先定义了一个字符串str,一个字符ch和一个子字符串sub。然后,我们使用indexOf()方法分别查找字符ch和子字符串sub在字符串str中的位置,并将结果存储在变量index1index2中。最后,我们打印出这两个位置。

输出结果如下:

The index of 'W' in the string is: 7
The index of "World" in the string is: 7

需要注意的是,indexOf()方法返回的是指定字符或子字符串在字符串中首次出现的位置,而不是最后一个出现的位置。如果需要查找最后一个出现的位置,可以使用lastIndexOf()方法。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java怎么赋值