Meanwhile, StringComparer is a class we can use to compare 2 strings in a certain way. We can use both of these types by including the System namespace in a C# program.
StringComparison example. This enum affects the result of a common method used. The IndexOf method on the String type accepts an argument of type StringComparison.
And The StringComparison argument dictates the specifics of the character searching.
Detail In this example, all of the StringComparison constants result in the same value from the IndexOf method.
Also StringComparison helps when optimizing string performance. For the best performance, the Ordinal enum is useful.
using System;
//// Use the StringComparison enumerated type on the string input.//
const string input = "Dot Net Perls";
Console.WriteLine(input.IndexOf("Net", StringComparison.Ordinal));
Console.WriteLine(input.IndexOf("net", StringComparison.OrdinalIgnoreCase));
Console.WriteLine(input.IndexOf("Net", StringComparison.CurrentCulture));
Console.WriteLine(input.IndexOf("net", StringComparison.CurrentCultureIgnoreCase));
Console.WriteLine(input.IndexOf("Net", StringComparison.InvariantCulture));
Console.WriteLine(input.IndexOf("net", StringComparison.InvariantCultureIgnoreCase));4
4
4
4
4
4
OrdinalIgnoreCase. We use the string.Equals method with the StringComparison OrdinalIgnoreCase argument. The first 2 arguments are the 2 strings you are trying to compare.
And The final argument is an instance of the StringComparison enum. Any valid value can be used. We can access it like any other enum.
Here Equals() called with OrdinalIgnoreCase returns true if the strings are equal when lowercase and uppercase are different.
A summary. StringComparison lets us specify the internal behavior of the string methods (such as IndexOf). StringComparer also provides a way to specify string comparisons.
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 17, 2023 (edit).