C# 字符串 - CompareOrdinal() 方法
C# 字符串 CompareOrdinal() 方法用于比较两个字符串对象,比较每个字符串中对应字符对象的序数(二进制)值。
语法
以下是 C# 字符串 CompareOrdinal() 方法的语法 -
public static int CompareOrdinal(string strA, string strB);
参数
此方法接受以下参数 -
- strA:第一个要比较的字符串。
- strB:第二个要比较的字符串。
返回值
此方法返回一个整数,表示两个字符串之间的词汇关系。
- 如果整数小于 0:strA 小于 strB
- 如果整数为 0:strA 等于 strB
- 如果整数大于 0:strA 大于 strB
示例 1:比较两个字符串
以下是CompareOrdinal() 方法比较两个字符串 −
using System; class Sample { public static void Main() { String str1 = "ABCD"; String str2 = "abcd"; int result; Console.WriteLine("Compare the numeric values of the corresponding Char objects in each string."); Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2); result = String.CompareOrdinal(str1, str2); Console.WriteLine("result: " + result); } }
输出
以下是输出 -
Compare the numeric values of the corresponding Char objects in each string. str1 = 'ABCD', str2 = 'abcd' result: -32
示例 2:比较两个相同的字符串
我们来看另一个示例。这里,我们使用 CompareOrdinal() 方法比较两个具有相同值的字符串 -
using System; class Sample { public static void Main() { String str1 = "ABCD"; String str2 = "ABCD"; int result; Console.WriteLine("Compare the numeric values of the corresponding Char objects in each string."); Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2); result = String.CompareOrdinal(str1, str2); Console.WriteLine("result: " + result); } }
输出
以下是输出 -
Compare the numeric values of the corresponding Char objects in each string. str1 = 'ABCD', str2 = 'ABCD' result: 0
示例 3:如果第二个字符串小于第一个字符串会怎样?
在本例中,我们使用 CompareOrdinal() 方法。如果第二个字符串小于第一个字符串,则此方法返回一个正整数 -
using System; class Sample { public static void Main() { String str1 = "tutorix"; String str2 = "tutorialspoint"; Console.WriteLine("Compare the numeric values of the corresponding Char objects in each string."); Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2); int result = String.CompareOrdinal(str1, str2); Console.WriteLine("result: " + result); } }
输出
以下是输出 -
Compare the numeric values of the corresponding Char objects in each string. str1 = 'tutorix', str2 = 'tutorialspoint' result: 23
示例 4:显示带有条件检查的语句
以下示例演示如何使用 CompareOrdinal() 方法比较两个字符串 (str1 和 str2)。根据比较结果,显示一条语句,指定 str1 是小于、等于还是大于 str2 -
using System; class Program { static void Main() { string str1 = "hey this is tutorix"; string str2 = "Hey This is tutorialspoint"; int result = String.CompareOrdinal(str1, str2); if (result < 0) Console.WriteLine($"{str1} is less than {str2}"); else if (result == 0) Console.WriteLine($"{str1} is equal to {str2}"); else Console.WriteLine($"{str1} is greater than {str2}"); } }
输出
以下是输出 -
hey this is tutorix is greater than Hey This is tutorialspoint