String.CompareTo 方法 (String) 将此实例与指定的 String 对象进行比较。using System;public class CompareToTest { public static void Main() { string strFirst = "Goodbye"; string strSecond = "Hello"; string strThird = "a small string"; string strFourth = "goodbye"; // compare a string to itself Console.WriteLine (CompareStrings(strFirst, strFirst)); Console.WriteLine (CompareStrings(strFirst, strSecond)); Console.WriteLine (CompareStrings(strFirst, strThird)); // compare a string to another string that varies only by case Console.WriteLine (CompareStrings(strFirst, strFourth)); Console.WriteLine (CompareStrings(strFourth, strFirst)); } private static string CompareStrings( string str1, string str2 ) { // compare the values, using the CompareTo method on the first string int cmpVal = str1.CompareTo(str2); if (cmpVal == 0) // the values are the same return "The strings have the same value!"; else if (cmpVal > 0) // the first value is greater than the second value return "The first string is greater than the second string!";
else // the second string is greater than the first string return "The second string is greater than the first string!"; } }
将此实例与指定的 String 对象进行比较。using System;public class CompareToTest {
public static void Main() { string strFirst = "Goodbye";
string strSecond = "Hello";
string strThird = "a small string";
string strFourth = "goodbye"; // compare a string to itself
Console.WriteLine (CompareStrings(strFirst, strFirst)); Console.WriteLine (CompareStrings(strFirst, strSecond));
Console.WriteLine (CompareStrings(strFirst, strThird)); // compare a string to another string that varies only by case
Console.WriteLine (CompareStrings(strFirst, strFourth));
Console.WriteLine (CompareStrings(strFourth, strFirst));
} private static string CompareStrings( string str1, string str2 ) { // compare the values, using the CompareTo method on the first string
int cmpVal = str1.CompareTo(str2); if (cmpVal == 0) // the values are the same
return "The strings have the same value!"; else if (cmpVal > 0) // the first value is greater than the second value
return "The first string is greater than the second string!";
else // the second string is greater than the first string
return "The second string is greater than the first string!";
}
}