How To Compare Strings In A Sort Order C#
Maybe your like
Overview
We can compare strings with the help of CompareTo() method in C#. You can compare a string with another string to know if it precedes, follows, or appears in the position as the other in the sort order.
An integer value is returned when the CompareTo() method is used.
Syntax
Following is the syntax of the CompareTo() method:
public int CompareTo() (string str);Parameters
CompareTo() method takes the following parameter:
str: This is the string you want to compare with the second string instance.
Return value
The value returned is an integer of type int32. It returns a value less than 0 if the instances precedes str. A 0 is returned if they are both in the same position in the sort order. It returns a value greater than 0 if str is after the instance or the str is null.
Code example
In the code example below, we will create strings and compare their sort order using the CompareTo() method:
// using System;// create compare string order classclass CompareSortOrder{ // main method static void Main() { // define and initialize strings string first = "Edpresso"; string second = "is "; string third = "the"; string fourth = "best"; string fifth = "Edpresso"; // compare strings int a = first.CompareTo(second); int b = second.CompareTo(third); int c = third.CompareTo(fourth); int d = fourth.CompareTo(fifth); int e = fifth.CompareTo(first); // print returned values to the console System.Console.WriteLine(a); // -1 System.Console.WriteLine(b); // -1 System.Console.WriteLine(c); // 1 System.Console.WriteLine(d); // -1 System.Console.WriteLine(e); // 0 }}RunIn the code above:
-
In line 24, -1 is returned because Edpresso precedes is in the sort order.
-
In line 25, is precedes The, and hence, -1 is returned. The same pattern goes for line 27.
-
In line 26, best precedes the. So the second string precedes the string instance, thus 1 is returned.
-
In line 28, 0 is returned because the first string Edpresso and the second string Edpresso are both on the same position in the sort order.
Relevant Answers
Explore Courses
Free Resources
License: Creative Commons-Attribution-ShareAlike 4.0 (CC-BY-SA 4.0)Tag » How To Compare String In C#
-
How To Compare Strings - C# Guide - Microsoft Docs
-
Compare Strings In C# - TutorialsTeacher
-
How To Compare Strings In C#
-
C# String Compare() Method - Javatpoint
-
How To Compare Strings In C#? - GeeksforGeeks
-
C# String Compare() (With Examples) - Programiz
-
How To Compare Two Strings In C# - TechieClues
-
4 Ways Of C# String Comparison: [Compare, Equals, CompareTo And)
-
Comparing Strings | Manipulating Strings In C# | Peachpit
-
Compare String And Object In C# - Stack Overflow
-
2.7. Controlling Case Sensitivity When Comparing Two Strings
-
How To Use C# String Compare - C# Tutorial And Source Code
-
How String Comparison Works In .NET - C# Video Tutorial - LinkedIn
-
C# String Compare And CompareTo - Dot Net Perls