在 C# 中按字典順序比較兩個字串


如需在 C# 中比較字串,請使用比較()方法。它比較兩個字串並返回以下整數 -

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.

在字串中設定兩個字串。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

更新於:2020 年 6 月 19 日

2K+ 瀏覽量

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.