Contains String MethodUse the Contains method on the string type. Examine the implementation of Contains.
This page was last reviewed on May 31, 2021.
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.
Shows a string method
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.
Detail To test for strings in a case-insensitive way, try passing OrdinalIgnoreCase to the Contains() method.
Shows a string method
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 31, 2021 (edit).
© 2007-2023 Sam Allen.