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