C# Check if String contains Specified Substring
To check if a string str
contains specified substring value
, or say if specified substring is present in the string, use C# String.Contains(String)
method.
Call Contains()
method on the string str
and pass the substring value
as argument. Contains()
method returns True if string str
contains the substring value
.
Examples
1. Check if string contains the substring ‘cd’
In the following program, we take a string in str
, and a search string in value
, and check if the string str
contains the string value
as a substring.
C# Program
using System;
class Example {
static void Main(string[] args) {
String str = "abcdefgh";
String value = "cd";
Boolean result = str.Contains(value);
Console.WriteLine($"Does string contain specified substring? {result}");
}
}
Output
Does string contain specified substring? True
2. Check if string contains substring ‘mno’
In this example, we have taken the string value and search string value, such that the search string is not present in the string as a substring.
If substring value
is not present in this string str
, then Contains()
method returns False
.
C# Program
using System;
class Example {
static void Main(string[] args) {
String str = "abcdefgh";
String value = "mno";
Boolean result = str.Contains(value);
Console.WriteLine($"Does string contain specified substring? {result}");
}
}
Output
Does string contain specified substring? False
3. Check if string contains substring ‘CD’, ignoring the case
If we would like to ignore case while checking if the substring is present in the string, you may specify to ignore case via StringComparison
object as shown in the following example.
C# Program
using System;
class Example {
static void Main(string[] args) {
String str = "abcdefgh";
String value = "CD";
StringComparison comp = StringComparison.OrdinalIgnoreCase;
Boolean result = str.Contains(value, comp);
Console.WriteLine($"Does string contain specified substring? {result}");
}
}
Output
Does string contain specified substring? True
Conclusion
In this C# Tutorial, we learned how to check if specified substring is present in a given string.