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


Java Java.lang.String.lastIndexOf()用法及代碼示例


描述

這個java.lang.String.lastIndexOf(String str, int fromIndex) 方法返回此字符串中最後一次出現的指定子字符串的索引,從指定索引開始向後搜索。返回的整數是最大值 k 使得 -

k >= Math.min(fromIndex, this.length()) && this.startsWith(str, k),如果不存在這樣的 k 值,則返回 -1。

聲明

以下是聲明java.lang.String.lastIndexOf()方法

public int lastIndexOf(String str, int fromIndex)

參數

  • str- 這是要搜索的子字符串。

  • fromIndex- 這是開始搜索的索引。

返回值

此方法返回此字符串中最後一次出現的指定子字符串的索引。

異常

NA

示例

下麵的例子展示了 java.lang.String.lastIndexOf() 方法的用法。

package com.tutorialspoint;

import java.lang.*;

public class StringDemo {

   public static void main(String[] args) {

      String str1 = "Collections of tutorials at tutorials point";
     
      /* search starts from index 17 and if located it returns 
         the index of the first character of the last substring "tutorials" */
      System.out.println("index = " + str1.lastIndexOf("tutorials", 17)); 

      /* search starts from index 9 and returns -1 as substring "admin"
         is not located */
      System.out.println("index = " + str1.lastIndexOf("admin", 9));     
   }
}

讓我們編譯並運行上麵的程序,這將產生以下結果 -

index = 15
index = -1

相關用法


注:本文由純淨天空篩選整理自 Java.lang.String.lastIndexOf() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。