How to Check if String Contains Substring in C#
In C#, you can check if a string contains a substring using the
Contains method. It returns true if the substring is found and false otherwise. For example, myString.Contains("text") checks if "text" is inside myString.Syntax
The Contains method is called on a string variable and takes another string as an argument. It returns a boolean value indicating if the substring exists inside the main string.
- string.Contains(substring): Checks if
substringis part ofstring. - Returns
trueif found,falseif not.
csharp
bool result = mainString.Contains(substring);
Example
This example shows how to use Contains to check if one string is inside another and prints the result.
csharp
using System; class Program { static void Main() { string mainString = "Hello, welcome to C# programming!"; string substring = "welcome"; bool contains = mainString.Contains(substring); Console.WriteLine($"Does the main string contain '{substring}'? {contains}"); } }
Output
Does the main string contain 'welcome'? True
Common Pitfalls
One common mistake is ignoring case sensitivity. The Contains method is case-sensitive, so "Welcome" and "welcome" are different. To check without case sensitivity, convert both strings to the same case using ToLower() or ToUpper().
Another pitfall is passing null as the substring, which causes an exception.
csharp
string mainString = "Hello, welcome to C# programming!"; string substring = "Welcome"; // Case-sensitive check (will be false) bool result1 = mainString.Contains(substring); // Case-insensitive check (convert both to lower case) bool result2 = mainString.ToLower().Contains(substring.ToLower()); Console.WriteLine(result1); // False Console.WriteLine(result2); // True
Output
False
True
Quick Reference
| Method | Description | Example |
|---|---|---|
| Contains | Checks if substring exists (case-sensitive) | str.Contains("text") |
| ToLower + Contains | Case-insensitive check | str.ToLower().Contains(sub.ToLower()) |
| IndexOf | Returns position or -1 if not found | str.IndexOf("text") >= 0 |
Key Takeaways
Use
Contains to check if a string includes a substring in C#.Contains is case-sensitive; use ToLower() or ToUpper() for case-insensitive checks.Passing
null to Contains causes an error; always ensure substring is not null.For position info,
IndexOf can be used instead of Contains.