contains():
The contains() method is a part of the String class. It is used to check whether a specific substring exists within a given string.
The method returns a boolean value indicating whether the substring is found or not.
The general syntax of the contains()
method is:
public boolean contains(CharSequence sequence)
Here's an explanation of how the contains()
method works:
sequence: This parameter represents the character sequence or substring that you want to check for within the string.
The contains() method performs a simple search within the string to determine if the specified substring is present. It returns true if the substring is found, and false otherwise.
Here's an example to illustrate the usage of the contains()
method:
String str = "Hello, World!";
boolean containsWorld = str.contains("World");
System.out.println("Contains 'World': " + containsWorld); // Output: true
boolean containsJava = str.contains("Java");
System.out.println("Contains 'Java': " + containsJava); // Output: false
- In the above example, we have a string
str
that contains the text "Hello, World!". - We use the
contains()
method to check if the substring "World" and "Java" exist within the string. - The method returns
true
for "World" since it is present in the string, while it returnsfalse
for "Java" since it is not found..
- The contains() method is case-sensitive, meaning it considers the exact case of the characters in the substring.
- If you need a case-insensitive search, you can convert both the string and the substring to lowercase or uppercase using the toLowerCase() or toUpperCase() methods before performing the contains() check.
- The contains() method is useful when you need to determine the presence of a specific substring within a larger string. It provides a convenient way to perform substring checks in Java.
Some Example :
1.Basic substring existence:
Input: "Hello, World!", substring: "World"
Expected output: true
Explanation: The substring "World" is present in the given string.
2.Substring not found:
Input: "Hello, World!", substring: "Java"
Expected output: false
Explanation: The substring "Java" is not present in the given string.
3.Case sensitivity:
Input: "Hello, World!", substring: "world"
Expected output: false
Explanation: The contains() method is case-sensitive, so the lowercase substring "world" is not found in the given string.
4.Empty string:
Input: "", substring: "Hello"
Expected output: false
Explanation: The empty string does not contain any substring.
5.Empty substring:
Input: "Hello, World!", substring: ""
Expected output: true
Explanation: An empty substring is considered to be present in any non-empty string.
6.Overlapping substrings:
Input: "Hello, Hello!", substring: "Hello"
Expected output: true
Explanation: The substring "Hello" is present twice in the given string.
0 Comments