C# String.Compare method compares two strings in C#. You can also use C# String.Equals method and StringComparer class and its method. This article and code examples demonstrate how to compare strings in C# using these different methods. Show Using String.EqualsThe simplest form of comparting two string for the same value is using String.Equals method. If both strings are equal, the method returns true; else returns false. The code sample in Listing 1 is an example of comparing two strings using String.Equals method.
Listing 1. The output of Listing 1 looks like Figure 1. Figure 1. Using String.CompareString.Compare method compares two strings and returns an integer value. The return value of the Compare method can be less than zero, greater than zero or equals to zero.
The code sample in Listing 2 is an example of comparing two strings using String.Compare method.
Listing 2. Using CompareTo MethodCompareTo method is an instance method of string class. It compares a value (either a string or on object) with a string instance. Return values of this method are same as the Compare method. The code sample in Listing 3 is an example of comparing two strings using the CompareTo method.
Listing 3. Using StringComparerYou can also use the StringComparer class to compare two strings. The code sample in Listing 4 is an example of comparing two strings using the StringComparer.Compare method.
Listing 4. Complete Code ExampleListing 5 is the complete program written in .NET Core and C#.
Listing 5. SummaryThis article and code sample demonstrated how to comapre two strings in C# and .NET Core using different methods. |