Java.lang.String.lastIndexOf() 方法



描述

java.lang.String.lastIndexOf(int ch, int fromIndex) 方法返回在此字串中指定字元最後一次出現的索引,從指定的索引開始向後搜尋。

宣告

以下是 java.lang.String.lastIndexOf() 方法的宣告

public int lastIndexOf(int ch, int fromIndex)

引數

  • ch − 字元的 Unicode 碼點值。

  • fromIndex − 開始搜尋的索引。如果它大於或等於此字串的長度,則其效果與等於此字串長度減 1 相同:可以搜尋整個字串。如果它是負數,則其效果與等於 -1 相同:返回 -1。

返回值

此方法返回在此物件所表示的字元序列中,小於或等於 fromIndex 的字元最後一次出現的索引,如果該字元在此點之前未出現,則返回 -1。

異常

示例

以下示例顯示了 java.lang.String.lastIndexOf() 方法的用法。

package com.tutorialspoint;

import java.lang.*;

public class StringDemo {

   public static void main(String[] args) {

      String str = "This is tutorialspoint";
   
      /* returns positive value(last occurrence of character t) as character
         is located, which searches character t backward till index 14 */
      System.out.println("last index of letter 't' =  "
         + str.lastIndexOf('t', 14)); 
      
      /* returns -1 as character is not located under the give index,
         which searches character s backward till index 2 */
      System.out.println("last index of letter 's' =  "
         + str.lastIndexOf('s', 2)); 
      
      // returns -1 as character e is not in the string
      System.out.println("last index of letter 'e' =  "
         + str.lastIndexOf('e', 5));
   }
}

讓我們編譯並執行上述程式,這將產生以下結果:

last index of letter 't' = 10
last index of letter 's' = -1
last index of letter 'e' = -1
java_lang_string.htm
廣告