C# 字符串比较

说明

比较字符串并非比较字符串的长度, 而是比较字符串在英文字典中的位置.

字符在词典中从大到小的顺序为 ZzYy....BbAa9876543210

语法

比较字符串的语法有三种

  • String.Compare(S1,S2)
    S1, S2为两个字符串, 从首字符开始比较, 如果S1>S2, 则返回数字1; 如果S1=S2,则返回数字 0; 如果S1
  • S1.Compare(S2)
    同上
  • S1.Equals(S2)
    如果S1, S2为两个字符串字符相等,则返回数字 True ,否则返回False;

实例

using System;
namespace CsharpCode
{
    class Program
    {
        static void Main(string[] args)
        {
            String S11 = "A";
            String S12 = "B";
            //Compare
            int t = String.Compare(S11,S12);
            Console.WriteLine(t);

            //CompareTo
            int j=S12.CompareTo(S11);
            Console.WriteLine(j);

            //Equals
            bool bl;
            bl = S11.Equals(S12);
            Console.WriteLine(bl);

            //from large to small:  ZzYy....BbAa9876543210
            String[] S1 ={"A","B","A","A","a","a","1A","A1","1A","2A"};
            String[] S2 ={"B","A","a","b","A","a","A1","1A","2A","1A"};

            for (int i=0;i

输出结果为

-1
1
False
Compare A with B: Resault = -1
Compare B with A: Resault = 1
Compare A with a: Resault = 1
Compare A with b: Resault = -1
Compare a with A: Resault = -1
Compare a with a: Resault = 0
Compare 1A with A1: Resault = -1
Compare A1 with 1A: Resault = 1
Compare 1A with 2A: Resault = -1
Compare 2A with 1A: Resault = 1

你可能感兴趣的:(C# 字符串比较)