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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 17, 2023 (edit).