當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java 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。

異常

NA

示例

下麵的例子展示了 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.lastIndexOf() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。