C# `String.Contains()` Method: Efficient Substring Searching
Learn how to use C#'s `String.Contains()` method for efficient substring searches. This tutorial explains its functionality, demonstrates its usage with code examples, and highlights its application in various string manipulation and data processing tasks.
Using the C# `String.Contains()` Method
Introduction
The Contains()
method in C# is a simple yet powerful way to check if a string contains a specific substring. It returns true
if the substring is found, and false
otherwise.
Method Signature
The method signature is straightforward:
Method Signature
public bool Contains(String str);
Parameters
str
: The substring you're searching for within the main string.
Return Value
The method returns a Boolean value:
true
: If the substringstr
is found within the string.false
: If the substringstr
is not found.
Example: Checking for Substrings
This example demonstrates how to use Contains()
to check if one string contains another.
Example Program
using System;
public class StringExample {
public static void Main(string[] args) {
string s1 = "Hello ";
string s2 = "He";
string s3 = "Hi";
Console.WriteLine(s1.Contains(s2)); // True
Console.WriteLine(s1.Contains(s3)); // False
}
}
Example Output
True
False
Explanation
The code checks if s1
contains s2
("He") and s3
("Hi"). The first check returns true
because "He" is a substring of "Hello ", while the second returns false
.
Conclusion
The Contains()
method is a simple and efficient way to perform substring checks in C#. It's a fundamental tool for string manipulation and data validation.