Home »
C# Tutorial
C# String.Contains() Method with Example
In this tutorial, we will learn about the String.Contains() method with its usage, syntax, and examples.
By IncludeHelp Last updated : April 07, 2023
C# String.Contains() Method
The String.Contains() method is used to check whether a given string contains a substring or not, we can use this method when we need to check whether a part of the string (substring) exists in the string.
Syntax
bool String.Contains(String substring);
The method is called with "this" string i.e. the string in which we have to check the substring.
Parameter(s)
- substring – is the part of the string to be checked.
Return Value
bool – it returns "True" if substring exists in the string or it returns "False" if substring does not exist in the string.
Note: This method is case-sensitive.
Input/Output Example
Input:
string str = "Hello world!";
string str1 = "world";
string str2 = "Hi";
Function call:
str.Contains(str1);
str.Contains(str2);
Output:
True
False
C# String.Contains() Method Example 1
using System;
class IncludeHelp {
static void Main() {
// declaring string variables
string str = "Hello world!";
string str1 = "world";
string str2 = "Hi";
// checking substring
Console.WriteLine("str.Contains(str1): " + str.Contains(str1));
Console.WriteLine("str.Contains(str2): " + str.Contains(str2));
}
}
Output
str.Contains(str1): True
str.Contains(str2): False
C# String.Contains() Method Example 2
using System;
class IncludeHelp {
static void Main() {
// declaring string variables
string address = "102, Nehru Place, New Delhi, India.";
string area1 = "Nehru Place";
string area2 = "Sant Nagar";
//checking and printing the result
if (address.Contains(area1)) {
Console.WriteLine(area1 + " exists in the address " + address);
} else {
Console.WriteLine(area1 + " does not exist in the address " + address);
}
if (address.Contains(area2)) {
Console.WriteLine(area2 + " exists in the address " + address);
} else {
Console.WriteLine(area2 + " does not exist in the address " + address);
}
}
}
Output
Nehru Place exists in the address 102, Nehru Place, New Delhi, India.
Sant Nagar does not exist in the address 102, Nehru Place, New Delhi, India.