C# Contains String MethodUse the Contains method on the string type. Examine the implementation of Contains.
dot net perls
Contains. This method searches strings. It checks if one substring is contained in another. It also provides a case-sensitive ordinal method for checking string contents.
C# return value. Contains returns true or false, not an index. It is the same as calling IndexOf and testing for -1 on your own. But Contains can be clearer to read.
Example. Contains is an instance method—you can call it on a specific string in your program. It has a bool result, which is true if the parameter is found, and false if it is not found.
Next The example program shows that Contains is case-sensitive when called with the default arguments.
Info In this program we call Contains 3 times. The string "abcdef" is tested with Contains.
Ignore case To test for strings in a case-insensitive way, try passing OrdinalIgnoreCase to the Contains() method.
C# program that uses Contains
using System; class Program { static void Main() { string value = "abcdef"; if (value.Contains("abc")) { Console.WriteLine("CONTAINS abc"); } if (!value.Contains("xyz")) { Console.WriteLine("DOES NOT CONTAIN xyz"); } if (value.Contains("ABC", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("CONTAINS ABC ignore case"); } } }
Internals. Contains calls IndexOf. When IndexOf returns -1, the string was not found. When Contains cannot find the string, it returns false. Contains offers no performance advantage.
Ordinal. This refers to a position number. When used with strings, it means that the characters are treated as numbers, not symbols.
And With StringComparison.Ordinal, all language characters are treated the same—regardless of the system locale.
Performance. Ordinal comparisons on strings are much faster than culture-dependent comparisons. This makes sense because it is easier for the system to compare numbers than symbols.
Summary. The simplest method to perform a task is often the best one. Contains is a simplified version of IndexOf. It allows you to easily check whether a string is contained in another.
© 2007-2021 sam allen. see site info on the changelog