EN
Java - find character index in string
0 points
In this article, we would like to show you how to find a character index in string in Java.
Quick solution:
xxxxxxxxxx
1
String text = "Dirask is awesome!";
2
3
int result = text.indexOf("D"); // 0
4
5
System.out.println(result);
In this example, we use String.indexOf()
method to find character index in the text
string.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "Dirask is awesome!";
5
6
int index1 = text.indexOf("D"); // 0
7
int index2 = text.indexOf("a"); // 3 (first occurrence)
8
9
int index3 = text.indexOf("Dirask"); // 0
10
int index4 = text.indexOf("is"); // 7
11
12
System.out.println(index1); // 0
13
System.out.println(index2); // 3 (first occurrence)
14
15
System.out.println(index3); // 0
16
System.out.println(index4); // 7
17
}
18
}
Output:
xxxxxxxxxx
1
0
2
3
3
0
4
7