Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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
false

Where 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
-1

Ignoring 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:

true

One 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:

true

Common 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
true

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.