How to check the occurrence of a value in a string in C#

There are times when you would want to check if a certain value is present in a particular string. This is very likely because such situations occur all the time. When dealing with strings, using the Contains() method is ideal.

The Contains() is a String method used to check the occurrence of a substring within another string. It returns true if the value occurs and false otherwise.

Syntax

string.Contains(substring)

Parameters

  • string: This is the string in which we want to check that whether a particular substring occurs or not.

  • substring: This is the string that’s presence we want to check inside the main string.

Return value

The returned value is a boolean. The value is true if the substring is present in the string. Otherwise, the value returned is false.

Code example

The following code snippet demonstrates the use of the Contains() method:

// create ContainsString class
class ContainsString
{
// main method
static void Main()
{
// defined and initialize strings
string name = "theodore kelechukwu onyejiaku";
string role = "software developer";
string subStr1 = "or";
string subStr2 = "on";
string subStr3 = "dev";
// Check if substrings are
//contained in our main strings
System.Console.WriteLine(name.Contains(subStr1));
System.Console.WriteLine(name.Contains(subStr2));
System.Console.WriteLine(name.Contains(subStr3));
System.Console.WriteLine(role.Contains(subStr1));
System.Console.WriteLine(role.Contains(subStr2));
System.Console.WriteLine(role.Contains(subStr3));
}
}

In the above code snippet, we can see that the strings subStr1 and subStr2 are present inside the string name. Hence, true values are returned. On the other hand, false values are returned for the remaining operations since those substrings are not part of the string.

Free Resources