How to check if a string contains a substring
Short answer
The contains() method returns true or false:
void main() {
String text = "Java is fun";
IO.println(text.contains("is"));
IO.println(text.contains("Python"));
}Output:
true
falseWhere the substring is
indexOf() returns the position of the first occurrence, or -1:
void main() {
IO.println("Java is fun".indexOf("is"));
IO.println("Java is fun".indexOf("Python"));
}Output:
5
-1Ignoring case
Bring both strings to the same case:
void main() {
String text = "Hello World";
String query = "WORLD";
IO.println(text.toLowerCase(Locale.ROOT).contains(query.toLowerCase(Locale.ROOT)));
}Output:
trueOne of several words
Check a list of words with anyMatch():
void main() {
var banned = List.of("spam", "scam");
String message = "This is not a scam";
IO.println(banned.stream().anyMatch(message::contains));
}Output:
trueCommon mistake
Confusing contains() with matches(). matches() checks that the whole string matches a regular expression, not just a part of it:
void main() {
IO.println("order 42".matches("\\d+"));
IO.println("order 42".matches(".*\\d+.*"));
}Output:
false
trueFunctions used in this recipe
- String.contains() — Checks whether a string contains a substring.
- String.indexOf() — Finds the position of the first occurrence of a character or a substring.
- String.matches() — Checks whether the whole string matches a regular expression.
- String.toLowerCase() — Returns a copy of the string with all letters in lower case.