The .Contains()
method determines whether a string
includes a particular character or substring. It returns true
if the character is included, otherwise the method returns false
. There are additional parameters that can modify the comparison rules.
Syntax
// Determines whether the String includes a given characterString.Contains(char);// Determines whether the String includes a given stringString.Contains(string);// Determines whether the String includes a given character considering the type of comparisonString.Contains(char, comparisonType)// Determines whether the String includes a given string considering the type of comparisonString.Contains(string, comparisonType)
.Contains()
takes the following arguments:
char
is a single character.string
is a sequence of characters.comparisonType
is an enumeration value that allows to add specific rules to compare strings such as culture, case, and sort. Passing as an additional argument:CurrentCulture
determines whether strings match culture-sensitive criteria.CurrentCultureIgnoreCase
same as above and ignores the case.InvariantCulture
determines whether strings match culture-sensitive criteria and the invariant culture.InvariantCultureIgnoreCase
same as above and ignores the case.Ordinal
determines whether strings match using binary sort rules.OrdinalIgnoreCase
same as above and ignores the case.
Example
The following example shows how we can use .Contains()
method
using System;
public class Example
{
public static void Main()
{
string stringToSeek = "The distance is nothing when one has a motive.";
string substring = "motive";
char character = 'l';
bool result;
See AlsoHow to Get Value from HashTable Collection in C# using Specified KeyHow to check if a hash contains a particular key in RubyC# | Check if a SortedList object contains a specific value - GeeksforGeeksHow to determine if a value exists in a linked list in C#// String.Contains(string)
result = stringToSeek.Contains(substring);
Console.WriteLine(result);
// String.Contains(char)
result = stringToSeek.Contains(character);
Console.WriteLine(result);
}
}
Here is the following output:
True
False
Codebyte Example
The example below determines whether the word helpful
is included in the particular string.