Java

Java indexof能否处理空字符串

小樊
81
2024-10-09 23:27:35
栏目: 编程语言

是的,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。

0
看了该问题的人还看了