C# Check if String contains Specified Character

To check if a string str contains specified character value, or say if specified character is present in the string, use C# String.Contains(Char) method.

Call Contains() method on the string str and pass the character value as argument. Contains() method returns True if str contains value.

Examples

1. Check if string contains character ‘c’

In the following program, we take a string in str, and a character in ch, and check if the string str contains the character ch.

C# Program

</>
Copy
using System;
 
class Example {
    static void Main(string[] args) {
        String str = "abcdefgh";
        Char ch = 'c';
        Boolean result = str.Contains(ch);
        Console.WriteLine($"Does string contain specified character? {result}");
    }
}

Output

Does string contain specified character? True

2. Check if string contains character ‘m’

In this example, we have taken the string value and character value, such that the character is not present in the string.

If char value is not present in this string str, then Contains() method returns False.

C# Program

</>
Copy
using System;
 
class Example {
    static void Main(string[] args) {
        String str = "abcdefgh";
        Char value = 'm';
        Boolean result = str.Contains(value);
        Console.WriteLine($"Does string contain specified character? {result}");
    }
}

Output

Does string contain specified character? False

3. Check if string contains character ‘E’, ignoring the case

If we would like to ignore case while checking if the char is present in the string, you may specify to ignore case via StringComparison object as shown in the following example.

C# Program

</>
Copy
using System;
 
class Example {
    static void Main(string[] args) {
        String str = "abcdefgh";
        Char value = 'E';
        StringComparison comp = StringComparison.OrdinalIgnoreCase;
        Boolean result = str.Contains(value, comp);
        Console.WriteLine($"Does string contain specified character? {result}");
    }
}

Output

Does string contain specified character? True

Conclusion

In this C# Tutorial, we learned how to check if specified character is present in a given string.