Java.lang.StringBuffer.lastIndexOf() Method



Description

The java.lang.StringBuffer.lastIndexOf(String str, int fromIndex) method returns the index within this string of the last occurrence of the specified substring.The argument fromIndex is the index to start the search from.

Declaration

Following is the declaration for java.lang.StringBuffer.lastIndexOf() method

public int lastIndexOf(String str, int fromIndex)

Parameters

  • str − This is the substring to search for.

  • fromIndex − This is the index to start the search from.

Return Value

This method returns the index within this sequence of the last occurrence of the specified substring.

Exception

NullPointerException − if str is null.

Example

The following example shows the usage of java.lang.StringBuffer.lastIndexOf() method.

package com.tutorialspoint;

import java.lang.*;

public class StringBufferDemo {

   public static void main(String[] args) {
  
      StringBuffer buff = new StringBuffer("tutorials point");
      System.out.println("buffer = " + buff);

      /* returns the index within this string of the rightmost occurrence of the
         specified substring */
      System.out.println("last index of i = " + buff.lastIndexOf("i"));
  
      // returns index as the substring is found with fromIndex 10
      System.out.print("last index of als = ");
      System.out.println(buff.lastIndexOf("als",10));

      // returns -1 as fromIndex 2 can't find the substring 
      System.out.print("last index of ori = "); 
      System.out.println(buff.lastIndexOf("ori",2));  
   }
}

Let us compile and run the above program, this will produce the following result −

buffer = tutorials point
last index of i = 12
last index of als = 6
last index of ori = -1
java_lang_stringbuffer.htm
Advertisements