What is the String.Contains method in C#?
Overview
In C#, String.Contains() is an instance method of the String class. It is used to find whether a given string contains characters. If it finds a matching substring in this particular string, it returns True. If not, it returns False.
Syntax
public bool Contains (string substring)
// or
public bool Contains (Char value)
Parameters
String substring // the string to be searched
// or
Char value // character to be seeked
Returns value
Boolean: It returns True or False based on whether the string contains the given substring.
If the passed substring is null, it
throws an ArgumentNullException error.
Code
class HelloWorld{static void Main(){string text = "The quick brown fox";string searchText = "quick";string searchText1 = "dog";bool result = text.Contains(searchText);bool result1 = text.Contains(searchText1);System.Console.WriteLine("The string '{0}' contains '{1}'? -> '{2}'", text, searchText, result); // TrueSystem.Console.WriteLine("The string '{0}' contains '{1}'? -> '{2}'", text, searchText1, result1); // False}}
Explanation
- Line 5–7: We create
stringobjects. - Line 9 and 10: We call the
String.Contains()method to check whether thesubstringis present in the original string. It doesn’t return any information about the position of the substring.
-
By default, this method performs a case-sensitive and culture-insensitive comparison.
-
The method has overloaded versions, which takes an additional parameter value of
StringComparisionenum to indicate what kind of culture-sensitivity and case-sensitivity is to be used while comparing strings.
Boolean Contains(Char, StringComparision)
Boolean Contains(String, StringComparision)