使用 C# 詞法比較兩個字串


要在 C# 中比較字串,請使用 compare() 方法。它將比較兩個字串並返回以下整數值 −

If str1 is less than str2, it returns -1.

If str1 is equal to str2, it returns 0.

If str1 is greater than str2, it returns 1.

在 String.compare() 方法中設定兩個字串並對其進行比較 −

string.Compare(string1, string2);

示例

可以嘗試執行以下程式碼以比較 C# 中的兩個字串。

即時演示

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
   class MyApplication {
      static void Main(string[] args) {
         string string1 = null;
         string string2 = null;
         string1 = "amit";
         string2 = "Amit";
         int myOutput = 0;
         myOutput = string.Compare(string1, string2);
         Console.WriteLine(myOutput.ToString());
         Console.ReadLine();
      }
   }
}

輸出

-1

更新於: 19-6-2020

2K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.