在 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.