Home »
.Net »
C# Programs
How to check whether string contains substring or not in C#?
C# - Check string contains substring or not: Here, we will learn how we can whether a string contains substring or not using string.Contains() method in C#.Net?
Given a string and substring and we have to check whether a substring contains in a string or not using C#.Net.
string.Contains()
string.Contains() method returns true if given substring is exists in the string or not else it will return false.
Syntax:
bool string.Contains(string substring);
Consider the program:
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
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 »