Java String indexOf()

indexOf() 方法用來搜尋字元或子字串在字串中第一次出現的位置。

語法

// 搜尋字元
string.indexOf(int ch)
string.indexOf(int ch, int fromIndex)

// 搜尋字串
string.indexOf(String str)
string.indexOf(String str, int fromIndex)
  • ch:要搜尋的字元
  • str:要搜尋的子字串
  • fromIndex:從哪個位置開始搜尋
  • 回傳:找到的位置索引,找不到回傳 -1

範例

String s = "Hello World";

// 搜尋字元
int index1 = s.indexOf('o');
System.out.println(index1);  // 4

// 搜尋字串
int index2 = s.indexOf("World");
System.out.println(index2);  // 6

// 找不到
int index3 = s.indexOf("Java");
System.out.println(index3);  // -1

從指定位置開始搜尋

String s = "Hello World";

// 從索引 5 開始搜尋 'o'
int index = s.indexOf('o', 5);
System.out.println(index);  // 7(找到第二個 'o')

lastIndexOf()

從後面開始搜尋:

String s = "Hello World";

// 最後一個 'o' 的位置
int last = s.lastIndexOf('o');
System.out.println(last);  // 7

// 最後一個 'l' 的位置
int lastL = s.lastIndexOf('l');
System.out.println(lastL);  // 9

實際應用

檢查字串是否包含

String s = "Hello World";

if (s.indexOf("World") != -1) {
    System.out.println("包含 World");
}

// 更簡潔的方式
if (s.contains("World")) {
    System.out.println("包含 World");
}

計算字元出現次數

String s = "Hello World";
int count = 0;
int index = 0;

while ((index = s.indexOf('o', index)) != -1) {
    count++;
    index++;  // 移到下一個位置繼續搜尋
}

System.out.println("'o' 出現 " + count + " 次");  // 2 次

計算子字串出現次數

String s = "ababab";
String target = "ab";
int count = 0;
int index = 0;

while ((index = s.indexOf(target, index)) != -1) {
    count++;
    index += target.length();
}

System.out.println("'ab' 出現 " + count + " 次");  // 3 次

取得檔案副檔名

String filename = "image.backup.png";

int lastDot = filename.lastIndexOf('.');
if (lastDot != -1) {
    String ext = filename.substring(lastDot + 1);
    System.out.println("副檔名:" + ext);  // png
}

分割路徑

String path = "/home/user/documents/file.txt";

int lastSlash = path.lastIndexOf('/');
String directory = path.substring(0, lastSlash);
String filename = path.substring(lastSlash + 1);

System.out.println("目錄:" + directory);   // /home/user/documents
System.out.println("檔名:" + filename);    // file.txt

indexOf vs contains

contains() 內部使用 indexOf(),兩者功能類似:

String s = "Hello World";

// 使用 indexOf
boolean hasWorld1 = s.indexOf("World") != -1;

// 使用 contains(更直觀)
boolean hasWorld2 = s.contains("World");

如果只需要判斷是否包含,建議使用 contains(),可讀性更好。