C# String Contains

Summary: in this tutorial, you will learn how to use the C# String Contains() method to check whether a substring is present within a given string.

Introduction to the C# String Contains method

The C# String Contains() method allows you to check whether a string is present in another string. Here’s the syntax of the Contains() method:

public bool Contains(string value)Code language: C# (cs)

The Contains() method accepts a parameter value with the String type.

The Contains() method returns true if a string value is present in the current string. If the string value is not present in the current string, the Contains() method returns false.

For example, the following program uses the Contains() method to check if the string "awesome" occurs in the string "C# is awesome":

using static System.Console;

var message = "C# is awesome";
var result = message.Contains("awesome");

WriteLine(result); // TrueCode language: C# (cs)

As expected, it returns true.

The following program outputs false because the string "C# is awesome" doesn’t have the substring "cool":

using static System.Console;

var message = "C# is awesome";
var result = message.Contains("cool");
WriteLine(result); // FalseCode language: C# (cs)

Besides accepting a string, the Contains() method has an overload that accepts a character as a parameter:

public bool Contains (char value);Code language: C# (cs)

For example:

using static System.Console;

var message = "C# is awesome";
var result = message.Contains('#');

WriteLine(result); // TrueCode language: C# (cs)

In this example, the Contains() method returns true because the message "C# is awesome" contains the character '#'.

By default, the Contains() method compares strings using an ordinal comparison, meaning that it considers both case sensitivity and culture insensitivity.

To perform a culture-sensitive comparison, you use the following overload version of the Contains() method:

public bool Contains (
    string value, 
    StringComparison comparisonType
);Code language: C# (cs)

In this syntax, the comparisonType is one of the enumeration values of the StringComparison enum, which specifies the rules for comparison.

The following example illustrates how to use the Contains() method with two different StringComparison enum values that compare string case-sensitively and case-insensitively:

using static System.Console;

var message = "C# is awesome";

var result = message.Contains("c",StringComparison.Ordinal);
WriteLine(result); // False

result = message.Contains("c", StringComparison.OrdinalIgnoreCase);
WriteLine(result); // TrueCode language: C# (cs)

Summary

  • Use the String Contains() method to check if a string or a character present in the current string.
Was this tutorial helpful ?