EN
Java - String indexOf() method example
5 points
Simple example:
xxxxxxxxxx
1
String text = "Here we are";
2
int index = text.indexOf("H"); // 0
3
4
System.out.println( text.indexOf("H") ); // 0
5
System.out.println( text.indexOf("e") ); // 1
6
System.out.println( text.indexOf("r") ); // 2
7
System.out.println( text.indexOf(" ") ); // 4
8
System.out.println( text.indexOf("we") ); // 5
9
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.
xxxxxxxxxx
1
public class Example1 {
2
3
public static void main(String[] args) {
4
5
String text = "Here we are";
6
int index = text.indexOf("we");
7
System.out.println(index); // 5
8
}
9
}
Output:
xxxxxxxxxx
1
5
Why indexOf() method printed index 5? Explanation below.
Why indexOf() method printed index 5?
Below code prints indexes of each character.
xxxxxxxxxx
1
public class IndexExplanation {
2
3
public static void main(String[] args) {
4
5
String text = "Here we are, we";
6
for (int i = 0; i < text.length(); i++) {
7
System.out.println("index: " + i + ", char: " + text.charAt(i));
8
}
9
}
10
}
Output:
xxxxxxxxxx
1
index: 0, char: H
2
index: 1, char: e
3
index: 2, char: r
4
index: 3, char: e
5
index: 4, char:
6
index: 5, char: w
7
index: 6, char: e
8
index: 7, char:
9
index: 8, char: a
10
index: 9, char: r
11
index: 10, char: e
12
index: 11, char: ,
13
index: 12, char:
14
index: 13, char: w
15
index: 14, char: e
Another short explanation of index
xxxxxxxxxx
1
// index: 0123456789..
2
String text = "Here we are";
3
// index of 'we' is 5
xxxxxxxxxx
1
public class Example3 {
2
3
public static void main(String[] args) {
4
5
String text = "Here we are, we";
6
int index = text.indexOf("we", 6);
7
System.out.println(index); // 13
8
}
9
}
Output:
xxxxxxxxxx
1
13
xxxxxxxxxx
1
public class Example4 {
2
3
public static void main(String[] args) {
4
5
String text = "Here we are";
6
int index = text.indexOf('w');
7
System.out.println(index); // 5
8
}
9
}
Output:
xxxxxxxxxx
1
5
xxxxxxxxxx
1
public class Example5 {
2
3
public static void main(String[] args) {
4
5
String text = "Here we are, we";
6
int index = text.indexOf('w', 6);
7
System.out.println(index); // 13
8
}
9
}
Output:
xxxxxxxxxx
1
13
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)