How to use C# string Compare

The String Compare function assumes a pivotal role in facilitating a lexicographic comparison between two distinct strings. This powerful functionality empowers developers to discern the relative order and arrangement of the strings based on the Unicode value assigned to each individual character within the respective strings.

int string.Compare(string str1,string str2)

It returns an Integer indication lexical relationship between the two comprehends

  1. string str1 : Parameter String
  2. string str2 : Parameter String

Integer : returns less than zero, zero or greater than zero.

  1. Less than zero : str1 is less than str2
  2. Zero : str1 is equal to str2
  3. Greater than zero : str1 is greater than str2

By invoking the Compare function, programmers can assess the relationships between characters in the strings and determine their positional hierarchy in accordance with the Unicode standard. This approach enables a comprehensive evaluation of the characters' significance, taking into account their specific Unicode values as a metric for comparison.

Unicode-based comparison

This Unicode-based comparison serves as a robust mechanism for establishing the relative "weight" or "magnitude" of each character within the strings being compared. Consequently, the Compare function provides a precise and nuanced understanding of the lexicographic order between the strings, facilitating decisions based on the specific requirements and objectives of the program.

Full Source C#
using System; using System.Windows.Forms; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string str1 = null; string str2 = null; str1 = "csharp"; str2 = "CSharp"; int result = 0; result = string.Compare(str1, str2); MessageBox.Show(result.ToString()); result = string.Compare(str1, str2, true); MessageBox.Show(result.ToString()); } } }

When you run this C# program first u will get -1 in message box and then 0


Through the utilization of the String Compare function in C#, developers can employ a sophisticated and systematic approach to string comparison, utilizing the Unicode values of the characters to discern their relative positioning. This in-depth assessment enables accurate and informed decisions when dealing with complex string manipulations and operations within the C# programming paradigm.