Determine whether a string contains a specific substring in C#
This post will discuss how to determine whether a string contains a specific substring in C#.
You can use the String.Contains() method, which returns a boolean value indicating whether the specified substring occurs within the string. The following example demonstrates its usage.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { string str = "100$"; string sub = "$"; bool exist = str.Contains(sub); Console.WriteLine(exist); // True } } |
The String.Contains() method performs a case-sensitive comparison. To perform the culture-insensitive comparison, you can directly call the Contains(String, StringComparison) overload instead.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { string str = "techie"; string sub = "Tech"; bool existIgnoreCase = str.Contains(sub, StringComparison.OrdinalIgnoreCase); Console.WriteLine(existIgnoreCase); // True } } |
Alternatively, you can call ToLower() or ToUpper() method before making case-insensitive searches, as shown below.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { string str = "techie"; string sub = "Tech"; bool existIgnoreCase = str.ToUpper().Contains(sub.ToUpper()); Console.WriteLine(existIgnoreCase); // True } } |
That’s all about determining whether a string contains a specific substring 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 :)