StringBuilder lastIndexOf() index in Java

lastIndexOf(): This method is available in java.lang.StringBuilder class of Java.

Syntax:

int java.lang.StringBuilder.lastIndexOf(String str, int fromIndex)

This method takes two arguments, one of type String and another of type int as its parameters. This method returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.

Parameters: Two parameters are required for this method.

str: the substring to search for.fromIndex the index to start the search from.

Returns: the index of the last occurrence of the specified substring, searching backward from the specified index, or -1 if there is no such occurrence.

Exceptions: NA

For Example:

StringBuilder str = new StringBuilder("Hello World")

String str1 = "l"

int fromIndex = 4

str.lastIndexOf(str1,fromIndex) = > It returns 3.

Approach

Java

public class LastIndexOfindex {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        String str1 = "l";
        int fromIndex = 4;
        System.out.println(str.lastIndexOf(str1, fromIndex));
    }
}

Output:

3

No comments:

Post a Comment