This article illustrates the different techniques to check string for a certain character in C#.

1. Using string.Contains() method

The string class contains the extension method Contains() that is overloaded for characters. It returns a boolean value true if the specified character occurs within the string; otherwise, false. The following code example demonstrates the usage of the String.Contains() method to perform case-sensitive and case-insensitive comparisons.

Download  Run Code

2. Using string.IndexOf() method

A better alternative to performing case-insensitive comparisons is using the string.IndexOf() method, which can accept StringComparison defining the culture, case, and sort rules for the search. The IndexOf() method returns the index of the first occurrence of the specified character in the string; -1 otherwise. This is demonstrated below:

Download  Run Code

That’s all about checking string for a certain character in C#.