Java .lastIndexOf()
Published Aug 22, 2022
The .lastIndexOf() method returns the index of the last (rightmost) occurrence of a substring in the StringBuilder. If a substring is not found, -1 is returned.
Syntax
myStringBuilder.lastIndexOf(substring, index);
The argument substring is the String being matched.
The index is an int argument that is optional. If provided, .lastIndexOf() returns the last occurrence of substring prior to that index in the StringBuilder.
Example
The following example creates a StringBuilder with a specified string and then uses .lastIndexOf() to find the final occurrence of a particular character:
import java.util.*;public class Example {public static void main(String[] args){StringBuilder str = new StringBuilder("Hello World!");System.out.println(str.toString());System.out.println(str.lastIndexOf("o"));}}
This produces the following output:
Hello World!7
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours