Home »
.Net »
C# Programs
How to check whether string contains substring or not in C#?
Given a string and substring and we have to check whether a substring contains in a string or not using C#.
[Last updated : March 19, 2023]
Checking if String Contains Substring
To check if string contains substring, we use string.Contains() method, which returns true if given substring is exists in the string or not else it will return false.
Syntax
bool string.Contains(string substring);
C# program to check if string contains substring
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1 {
class Program {
static void Main() {
string str = "Hello How are you? ";
if (str.Contains("How") == true) {
Console.WriteLine("Given string contains with in string");
} else {
Console.WriteLine("Given string does not contain with in string");
}
if (str.Contains("Who") == true) {
Console.WriteLine("Given string contains with in string");
} else {
Console.WriteLine("Given string does not contain with in string");
}
}
}
}
Output
Given string contains with in string
Given string does not contain with in string
Explanation
For first case: We are checking string (substring) "How" in the string str, the condition will be true because string str contains "How" but in other (second) case we are cheking "Who" which is not exists in string str i.e. string str does not contain the substring “Who”. Thus, condition will be false.
C# Basic Programs »