When it comes to programming, strings are the most basic data structures. A character list, or more precisely, an "array of characters," is what they're made up of. With the help of an example, we will learn how to use the function String lastIndexOf() in this article.
String toCharArray() Function
The lastIndexOf() method in Java is a built-in function that finds out the last occurrence of the specified character or a string. Generally, this method starts the search from the end of the string and proceeds backward from there otherwise, it starts from a specified index if it is provided in a method call.
Signature
There are 4 types of lastIndexOf() methods in Java. The signature of the methods are given below:
int lastIndexOf(int ch): It returns the last occurrence of character ch in the given String.
int lastIndexOf(int ch, int fromIndex): It returns an int value, representing the index of the first occurrence of the character in the string, or -1 if it never occurs.
int lastIndexOf(String str): Returns the last occurrence of substring str
in a String.
int lastIndexOf(String str, int fromIndex): Returns the last occurrence of str, and starts searching backward from the specified index “fromIndex”.
Parameters
ch: A char value i.e. a single character e.g. 'd'
fromIndex: index position from where the index of the char value or substring is searched and returned.
substring: substring that is to be searched in this string.
Example
Implementation
import java.io.*;
public class Example {
public static void main(String[] args) {
String str2="Welcome home Ninjas";
int ans1=str2.lastIndexOf('e');
int ans2=str2.lastIndexOf('e',5);
int ans3=str2.lastIndexOf("ome");
int ans4=str2.lastIndexOf("ome", 15);
System.out.println(ans1);
System.out.println(ans2);
System.out.println(ans3);
System.out.println(ans4);
}
}
You can also try this code with Online Java Compiler
What is the purpose of the String toCharArray function in Java?
The toCharArray() function in Java transforms a string into a sequence of characters. The length of the output array is the same as the length of the String.
What is the return type of StringlastIndexOf() in Java?
It returns an integer value.
What is String in Java?
The String is a Java class found in the Java.lang package. It isn't a primary data type like int or long. The string is a sequence of characters. Strings in Java are immutable, and the JVM stores all String objects in a String Pool.
What is the return type of String toCharArray() in Java?
It returns a newly allocated character array.
Conclusion
This article taught us about String lastIndexOf() method in Java and its implementation. The Java String lastIndexOf() method returns the last occurrence of any character or String. We have also seen some examples to understand better how this method works.