String.contains()
Checks whether a string contains a substring.
Available since: Java 5
Syntax
public boolean contains(CharSequence s)Parameters
| Parameter | Type | Description |
|---|---|---|
| s | CharSequence | The substring to look for — a String or a StringBuilder. |
Return value
booleantrue if the substring is found.
Examples
A simple check:
void main() {
String text = "Java is fun";
IO.println(text.contains("fun"));
IO.println(text.contains("Fun"));
}Output:
true
falseIgnoring case — convert both strings to the same case:
void main() {
String text = "Java is FUN";
String word = "fun";
IO.println(text.toLowerCase().contains(word.toLowerCase()));
}Output:
trueNotes
The method takes a string, not a char: contains('a') does not compile, write contains("a"). The empty string is contained in every string.
See also
- String.indexOf() — Finds the position of the first occurrence of a character or a substring.
- String.startsWith() — Checks whether a string starts with the given prefix.
- String.matches() — Checks whether the whole string matches a regular expression.
Related recipes
In the tutorial
- String methods — The main String methods in Java: searching, substring, changing case, strip, replace, split, join, repeat and string checks.