溫馨提示×

string怎么查找某個字符串的位置

小億
499
2024-03-15 16:51:52
欄目: 編程語言

要查找某個字符串在另一個字符串中的位置,可以使用字符串的indexOf方法。該方法返回要查找的子字符串在父字符串中第一次出現的位置,如果沒有找到則返回-1。

例如,我們要查找字符串"hello"在另一個字符串"hello world"中的位置可以這樣做:

String str = "hello world";
String subStr = "hello";

int index = str.indexOf(subStr);
if (index != -1) {
    System.out.println("子字符串在父字符串中的位置是:" + index);
} else {
    System.out.println("未找到子字符串");
}

上述代碼將會輸出:子字符串在父字符串中的位置是:0,表示"hello"在"hello world"中從第0個位置開始出現。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女