EN
Java - find text in string
0 points
In this article, we would like to show you how to find text in string in Java.
xxxxxxxxxx
1
String string = "Dirask is awesome!";
2
String text = "is";
3
4
// returns true if string contains text
5
boolean contains = string.contains(text);
6
System.out.println(contains); // true
or
xxxxxxxxxx
1
String string = "Dirask is awesome!";
2
String text = "is";
3
4
// returns index of the first occurrence of text in string
5
int index = string.indexOf(text);
6
System.out.println(index); // 7
In this example, we use String.contains()
method to check if the string
contains text
.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String string = "Dirask is awesome!";
5
String text = "is";
6
7
// returns true if string contains text
8
boolean contains = string.contains(text);
9
System.out.println("contains = " + contains); // true
10
}
11
}
Output:
xxxxxxxxxx
1
contains = true
In this example, we use String.indexOf()
method to find the index of the first occurrence of text
in the string
.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String string = "Dirask is awesome!";
5
String text = "is";
6
7
// returns index of the first occurrence of text in string
8
int index = string.indexOf(text);
9
System.out.println("index = " + index); // 7
10
}
11
}
Output:
xxxxxxxxxx
1
index = 7