温馨提示×

Java的indexof函数查找失败会怎样

小樊
81
2024-09-30 01:18:16
栏目: 编程语言

在Java中,indexOf函数用于查找子字符串在原字符串中首次出现的位置。如果查找失败,indexOf函数会返回-1。

例如:

String str = "Hello, world!";
int index = str.indexOf("world");

if (index != -1) {
    System.out.println("Found 'world' at index: " + index);
} else {
    System.out.println("'world' not found");
}

在这个例子中,"world"str中找到了,所以indexOf返回了一个非负整数(实际上是7)。但是,如果我们尝试查找一个不存在的子字符串,比如"planet"

int index = str.indexOf("planet");

if (index != -1) {
    System.out.println("Found 'planet' at index: " + index);
} else {
    System.out.println("'planet' not found");
}

这次"planet"没有在str中找到,所以indexOf返回了-1,输出结果是'planet' not found

0