Home » .Net

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.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.