EN
Java - String indexOf() method example
5
points
Simple example:
String text = "Here we are";
int index = text.indexOf("H"); // 0
System.out.println( text.indexOf("H") ); // 0
System.out.println( text.indexOf("e") ); // 1
System.out.println( text.indexOf("r") ); // 2
System.out.println( text.indexOf(" ") ); // 4
System.out.println( text.indexOf("we") ); // 5
System.out.println( text.indexOf("are") ); // 8
In this post we cover usage of String indexOf() method with simple code examples.
Definition:
We use Java String indexOf() method to find index of specified substring or char in given String.
1. String indexOf(String str)
public class Example1 {
public static void main(String[] args) {
String text = "Here we are";
int index = text.indexOf("we");
System.out.println(index); // 5
}
}
Output:
5
Why indexOf() method printed index 5? Explanation below.
2. Explanation of index
Why indexOf() method printed index 5?
Below code prints indexes of each character.
public class IndexExplanation {
public static void main(String[] args) {
String text = "Here we are, we";
for (int i = 0; i < text.length(); i++) {
System.out.println("index: " + i + ", char: " + text.charAt(i));
}
}
}
Output:
index: 0, char: H
index: 1, char: e
index: 2, char: r
index: 3, char: e
index: 4, char:
index: 5, char: w
index: 6, char: e
index: 7, char:
index: 8, char: a
index: 9, char: r
index: 10, char: e
index: 11, char: ,
index: 12, char:
index: 13, char: w
index: 14, char: e
Another short explanation of index
// index: 0123456789..
String text = "Here we are";
// index of 'we' is 5
3. String indexOf(String str, int fromIndex)
public class Example3 {
public static void main(String[] args) {
String text = "Here we are, we";
int index = text.indexOf("we", 6);
System.out.println(index); // 13
}
}
Output:
13
4. String indexOf(int ch)
public class Example4 {
public static void main(String[] args) {
String text = "Here we are";
int index = text.indexOf('w');
System.out.println(index); // 5
}
}
Output:
5
5. String indexOf(int ch, int fromIndex)
public class Example5 {
public static void main(String[] args) {
String text = "Here we are, we";
int index = text.indexOf('w', 6);
System.out.println(index); // 13
}
}
Output:
13
6. Versions of String indexOf method
Java provides 4 versions of indexOf with different parameters:
-
public int indexOf(String str)
-
public int indexOf(String str, int fromIndex)
-
public int indexOf(int ch)
-
public int indexOf(int ch, int fromIndex)
The most popular version of indexOf() method is
public int indexOf(String str)
Post thumbnail