C# program to check if a Substring is present in a Given String.
Use the contains() method in C# to check if a substring is in a given string.
Let us say the string is −
1 2 3 | United |
Within the string, you need to find the substring “Uni”. For that, use the contains method and use it like the following code snippet −
1 2 3 | res = str1.Contains(str2); |
Example
You can try to run the following code to find a substring in a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Program { static void Main(string[] args) { string str1 = "csharp-console-examples.com", str2 = "examples"; bool res; res = str1.Contains(str2); if (res) Console.Write("The substring " + str2 + " is in the string " + str1); else Console.Write("The substring " + str2 + " is not in the string " + str1); Console.ReadLine(); } } |
Output: