Java.lang.StringBuilder.lastIndexOf() Method

Advertisements


Description

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

Declaration

Following is the declaration for java.lang.StringBuilder.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.StringBuilder.lastIndexOf() method.

package com.tutorialspoint;

import java.lang.*;

public class StringBuilderDemo {

  public static void main(String[] args) {
  
    StringBuilder str = new StringBuilder("tutorials point");
    System.out.println("string = " + str);

    /* returns the index within this string of the rightmost occurrence of the
    specified substring */
    System.out.println("last index of i = " + str.lastIndexOf("i"));
  
    // returns index as the substring is found with fromIndex 10
    System.out.print("last index of als = ");
    System.out.println(str.lastIndexOf("als",10));
    
    // returns -1 as fromIndex 2 can't find the substring 
    System.out.print("last index of ori = "); 
    System.out.println(str.lastIndexOf("ori",2));  
  }
}  

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

string = tutorials point
last index of i = 12
last index of als = 6
last index of ori = -1



Advertisements
Advertisements