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.
Quick solution
String string = "Dirask is awesome!";
String text = "is";
// returns true if string contains text
boolean contains = string.contains(text);
System.out.println(contains); // true
or
String string = "Dirask is awesome!";
String text = "is";
// returns index of the first occurrence of text in string
int index = string.indexOf(text);
System.out.println(index); // 7
Practical examples
1. String.contains()
In this example, we use String.contains()
method to check if the string
contains text
.
public class Example {
public static void main(String[] args) {
String string = "Dirask is awesome!";
String text = "is";
// returns true if string contains text
boolean contains = string.contains(text);
System.out.println("contains = " + contains); // true
}
}
Output:
contains = true
2. String.indexOf()
In this example, we use String.indexOf()
method to find the index of the first occurrence of text
in the string
.
public class Example {
public static void main(String[] args) {
String string = "Dirask is awesome!";
String text = "is";
// returns index of the first occurrence of text in string
int index = string.indexOf(text);
System.out.println("index = " + index); // 7
}
}
Output:
index = 7