String Contains Examples
This page was last reviewed on Oct 27, 2023.
Dot Net Perls
Contains. This C# 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
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.
String IndexOf
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.
Here In this program we call Contains 3 times. The string "abcdef" is tested with Contains.
Tip To test for strings in a case-insensitive way, try passing OrdinalIgnoreCase to the Contains() method.
Note Internally contains calls IndexOf. Thus Contains offers no performance advantage over IndexOf.
Note 2 With StringComparison.Ordinal, all language characters are treated the same—regardless of the system locale.
Shows a string method
using System; 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"); }
Contains extension. This program tests the Contains extension method, which is a separate Contains from the string method. The extension method can be used on many types.
Info In this example, the first Contains call specifies the type parameter int in the angle brackets.
And This tells the C# compiler to select the extension method version of Contains, not the List type's version.
using System; using System.Collections.Generic; using System.Linq; var list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Use extension method. bool a = list.Contains<int>(7); // Use instance method. bool b = list.Contains(7); Console.WriteLine(a); Console.WriteLine(b);
True True
List Contains. There is also a Contains method on the C# List type. This method can be useful for searching for a value within a List.
List Contains
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 Oct 27, 2023 (rewrite).
© 2007-2024 Sam Allen.