Pages

lastindexOf() in Java strings ?

 lastindexOf() in java strings ?

>> In Java, lastindexOf() method is available in String class.
>> lastindexOf() method is used to retrieve the index of a given character or substring.
>> If it is not found it will return -1.

Java program using lastindexOf():

Lets say we have given input string:

java lastindexOf()
lastIndexOf()


public class lastIndex {

public static void main(String[] args) {
String s = "This is example string";

// lastIndexOf("String")
System.out.println("Position of x=" + s.lastIndexOf("x"));
System.out.println("Position of string=" + s.lastIndexOf("xample"));
System.out.println("if searched string not present=" + s.lastIndexOf("adsa"));

// lastIndexOf('character')
System.out.println("Position of character=" + s.lastIndexOf('i'));

// lastIndexOf("string","fromIndex")
System.out.println("Position of searched string from specified index=" + s.lastIndexOf("e", 9));

// lastIndexOf('character',"fromIndex")
System.out.println("Position of searched character from specified index=" + s.lastIndexOf('i', 6));

System.out.println("if searched substring not occur=" + s.lastIndexOf("a", 20));
}
}
Output:
lastIndexOf() in java
lastindexOf() java

As mentioned in above program we have 4 types lastindexOf() methods:
int lastindexOf(String substring) - returns the last index of given substring
int lastindexOf(int ch) - returns the last index of given character value
int lastindexOf(string substring,int fromindex) - returns last index position for the given substring and from index(before the index)
int lastindexOf(int ch,int fromindex) - returns index position for the given char value and from index(before the index)
Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.