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.

├Źndice
  1. String contains check in Java
  2. String contains check in Python
  3. Conclusion

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.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information