Java indexof能否处理空字符串

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

是的,Java中的indexOf()方法可以处理空字符串。当查找的字符串为空时,indexOf()方法会返回-1。以下是一个简单的示例:

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

        int index1 = str.indexOf("world");
        int index2 = emptyStr.indexOf("");

        System.out.println("Index of 'world' in str: " + index1); // 输出:Index of 'world' in str: 7
        System.out.println("Index of '' in emptyStr: " + index2); // 输出:Index of '' in emptyStr: 0
    }
}

在这个示例中,我们查找字符串"Hello, world!""world"的索引,以及空字符串""在自身中的索引。indexOf()方法分别返回7和0。

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

推荐阅读: java判断素数的方法有哪些