溫馨提示×

Java的indexof函數(shù)查找失敗會怎樣

小樊
81
2024-09-30 01:18:16
欄目: 編程語言

在Java中,indexOf函數(shù)用于查找子字符串在原字符串中首次出現(xiàn)的位置。如果查找失敗,indexOf函數(shù)會返回-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返回了一個非負(fù)整數(shù)(實際上是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,輸出結(jié)果是'planet' not found。

0