Java indexOf() method
Java indexOf() method
The indexOf() method is used to find the position of a character or substring within a string. It is a part of the String class and comes in several variations. The Java indexOf() method returns the index of the given character value or the substring. If it is not found, it returns -1. The index counter starts from zero.
Method signatures
The signature of indexOf methods are as follows:
- int indexOf(int ch): This method returns the index position for the given char value.
- int indexOf(int ch, int fromIndex) : This method returns the index position for the given char value and from index
- int indexOf(String Substring) : This method returns the index position for the given substring
- int indexOf(String substring, intIndex) : This method returns the index position for the given substring and from index
Example
A sample program to demonstrate the use of the indexOf() method is as follows:
package com.testingdocs.stringmethods;
public class IndexOfMethodDemo {
public static void main(String[] args) {
String str= "This is a sample sentence example.";
// index of character
int index_of_s=str.indexOf('s');
System.out.println(index_of_s);
// index of word or substring
int index_of_is1 = str.indexOf("is");
System.out.println(index_of_is1);
int index_of_sample = str.indexOf("sample");
System.out.println(index_of_sample);
}
}
Program Output
The program produces the following output:
3
2
10
Java Tutorials
Java Tutorial on this website:
For more information on Java, visit the official website :