C#入門6.4——字串的比較
阿新 • • 發佈:2019-02-20
例項:
用上述四種方法分別比較字串“Hello”與字串“Hi”是否相等或比較它們的大小。
方法:
1. ==
2.Equals方法
string.Equals(字串1,字串2)返回布林值
static void Main(string[] args) { //ToUpper方法可實現將英文轉換成大寫 string str1 = "Hello"; string str2 = "hi"; Console.WriteLine(string.Equals(str1,str2)); Console.ReadKey(); }
3.Compare有多個過載方法,這裡只列舉兩個
(1)Compare(字串1,字串2)
static void Main(string[] args)
{
//ToUpper方法可實現將英文轉換成大寫
string str1 = "Hello";
string str2 = "Hi";
Console.WriteLine(string.Compare(str1,str2));
Console.ReadKey();
}
輸出結果為-1,因為e比i小,所以對比到第二個字母的時候認為str1小於str2,等於就是0,大於就是1。
(2)Compare(字串1,字串2,布林值)
返回一個整數
當返回值小於0時,字串1小於字串2
等於大於同理。
布林值為true時,忽略大小寫進行比較。
(3)字串1.CompareTo(字串2);
一樣啦。