Check string for a certain character in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
using System; public static class StringExtensions { public static bool Contains(this string input, char c) { return input.Contains(c); } public static bool ContainsIgnoreCase(this string input, char c) { return input.ToLower().Contains(c.ToString().ToLower()); } } public class Example { public static void Main() { string s = "Hello"; Console.WriteLine(s.Contains('e')); // True Console.WriteLine(s.Contains('a')); // False Console.WriteLine(s.ContainsIgnoreCase('L')); // True } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
using System; public static class StringExtensions { public static bool Contains(this string s, char c) { return s.IndexOf(c, StringComparison.CurrentCultureIgnoreCase) != -1; } public static bool ContainsIgnoreCase(this string s, char c) { return s.IndexOf(c, StringComparison.InvariantCultureIgnoreCase) != -1; } } public class Example { public static void Main() { string s = "Hello"; Console.WriteLine(s.Contains('e')); // True Console.WriteLine(s.Contains('a')); // False Console.WriteLine(s.ContainsIgnoreCase('L')); // True } } |
That’s all about checking string for a certain character in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)