C# String Contains() Method

‮w//:sptth‬ww.theitroad.com

The Contains() method in C# is a string instance method that is used to determine whether a string contains a specified substring. It returns a Boolean value indicating whether the substring is found.

Here is an example of using the Contains() method:

string str = "The quick brown fox jumps over the lazy dog";
string substring = "fox";

if (str.Contains(substring))
{
    Console.WriteLine("The string contains the substring.");
}
else
{
    Console.WriteLine("The string does not contain the substring.");
}

In this example, we check whether the string str contains the substring "fox" using the Contains() method. Since the substring is found in the string, the Console.WriteLine() statement prints "The string contains the substring." to the console.

The Contains() method is case-sensitive by default, but you can specify a StringComparison argument to perform a case-insensitive search. Here is an example of a case-insensitive search:

string str = "The quick brown fox jumps over the lazy dog";
string substring = "FOX";

if (str.Contains(substring, StringComparison.OrdinalIgnoreCase))
{
    Console.WriteLine("The string contains the substring.");
}
else
{
    Console.WriteLine("The string does not contain the substring.");
}

In this example, we use the StringComparison.OrdinalIgnoreCase argument to perform a case-insensitive search for the substring "FOX". Since the substring is found in the string, the Console.WriteLine() statement prints "The string contains the substring." to the console.

Note that the Contains() method returns true if the specified substring is an empty string, since an empty string is considered to be a substring of any other string.