一、lastIndexOf方法的基本介紹
lastIndexOf方法是String類的一個實例方法,用於查找某個字元或子字元串在字元串中最後一次出現的位置。lastIndexOf方法有兩個重載版本:一個是只接受一個字元參數,另一個是接受一個字元串參數。下面是lastIndexOf方法的基本語法:
public int lastIndexOf(int ch) public int lastIndexOf(String str)
上述兩個方法都返回該字元或字元串在原字元串中最後一次出現的位置,如果沒有找到返回-1。
二、應用示例
1. 查找某個字元在字元串中最後一次出現的位置
下面是一個示例,演示如何使用lastIndexOf方法查找某個字元在字元串中最後一次出現的位置。
String str = "hello world"; int position = str.lastIndexOf('o'); System.out.println(position); // 輸出7
在上面的代碼中,我們查找字元串”hello world”中最後一次出現字元’o’的位置,由於字元’o’在字元串中出現了兩次,所以lastIndexOf方法返回第二個’o’所在的位置,即7。
2. 查找某個字元串在字元串中最後一次出現的位置
下面是一個示例,演示如何使用lastIndexOf方法查找某個字元串在字元串中最後一次出現的位置。
String str = "hello world"; int position = str.lastIndexOf("l"); System.out.println(position); // 輸出9
在上面的代碼中,我們查找字元串”hello world”中最後一次出現子字元串”l”的位置,由於子字元串”l”在字元串中出現了兩次,所以lastIndexOf方法返回第二個”l”所在的位置,即9。
3. 查找某個字元串最後一次出現的位置時指定起始位置
lastIndexOf方法還支持傳入第二個參數,用於指定起始位置。
String str = "hello world"; int position = str.lastIndexOf("l", 8); System.out.println(position); // 輸出3
在上面的例子中,我們從字元串”hello world”的第8個位置開始向前查找子字元串”l”最後一次出現的位置,結果得到位置3。
三、lastIndexOf方法的使用技巧
1. 使用lastIndexOf查找文件名後綴
下面是一個示例,演示如何使用lastIndexOf方法查找文件名後綴。
String fileName = "example.txt"; int dotPosition = fileName.lastIndexOf("."); if (dotPosition != -1) { String extension = fileName.substring(dotPosition + 1); System.out.println("File extension: " + extension); } else { System.out.println("No file extension found."); }
在上面的代碼中,我們首先使用lastIndexOf方法查找文件名中最後一個點號的位置,如果找到了,就從該位置後面截取子字元串,得到文件名後綴。如果沒有找到點號,說明文件名沒有後綴。
2. 使用lastIndexOf在字元串中查找多個關鍵字
下面是一個示例,演示如何使用lastIndexOf方法在字元串中查找多個關鍵字。
String str = "Find all occurrences of keywords in this text."; String[] keywords = {"all", "in", "text"}; for (String keyword : keywords) { int position = str.lastIndexOf(keyword); if (position != -1) { System.out.println("Found \"" + keyword + "\" at index: " + position); } else { System.out.println("Keyword \"" + keyword + "\" not found."); } }
在上面的代碼中,我們使用for循環遍歷一個關鍵字數組,對於每個關鍵字,使用lastIndexOf方法在字元串中查找其最後一次出現的位置,如果找到了,輸出該位置;如果沒有找到,輸出提示信息。
四、總結
本文介紹了Java中lastIndexOf方法的用法及應用技巧。我們學習了如何使用lastIndexOf方法查找某個字元或子字元串在字元串中最後一次出現的位置,以及如何指定起始位置進行查找。最後,我們還介紹了兩個常見的使用技巧:使用lastIndexOf方法查找文件名後綴,以及使用lastIndexOf方法在字元串中查找多個關鍵字。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/309812.html