indexOf() in java strings ?
>> In Java, indexOf() method is available in String class.
>> indexOf() 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 indexOf():
Lets say we have given input string:
public class indexOf {
public static void main(String[] args) {
String str = "This is example string";
// indexOf("String")
System.out.println("Position of x=" + str.indexOf("x"));
System.out.println("Position of string" + str.indexOf("xample"));
System.out.println("if searched string not present=" + str.indexOf("adsa"));
// indexOf('character')
System.out.println("Position of character=" + str.indexOf('g'));
// indexOf("string","fromIndex")
System.out.println("Position of searched string from specified index" + str.indexOf("e", 9));
// indexOf('character',"fromIndex")
System.out.println("Position of searched character from specified index=" + str.indexOf('i', 6));
System.out.println("if searched substring not occur=" + str.indexOf("a", 20));
}
}
Output:
As mentioned in above program we have 4 types indexOf() methods:
int indexOf(String substring) - returns the index of given substring
int indexOf(int ch) - returns the index of given character value
int indexOf(string substring,int fromindex) - returns index position for the given substring and from index
int indexOf(int ch,int fromindex) - returns index position for the given char value and from index
Please comment below to feedback or ask questions.
No comments:
Post a Comment
Please comment below to feedback or ask questions.