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.

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

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

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.