String contains check: How to check if one string is contained within another
Checking if one string is contained within another is a common task in programming. Fortunately, most programming languages provide a built-in method or function for this task.
String contains check in Java
In Java, the String
class provides the contains()
method to check if a string is contained within another string. The method returns a boolean value, true
if the string contains the specified sequence of characters, and false
otherwise.
String str1 = "Hello, World!";
String str2 = "World";
if (str1.contains(str2)) {
System.out.println("str1 contains str2");
} else {
System.out.println("str1 does not contain str2");
}
String contains check in Python
In Python, the in
keyword can be used to check if a string is contained within another string. The keyword returns a boolean value, True
if the string contains the specified sequence of characters, and False
otherwise.
str1 = "Hello, World!"
str2 = "World"
if str2 in str1:
print("str1 contains str2")
else:
print("str1 does not contain str2")
Conclusion
Checking if one string is contained within another is a simple task, and most programming languages provide a built-in method or function for this purpose. Java provides the contains()
method and Python provides the in
keyword for this task.
Leave a Reply
Related posts