当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C# String.Compare()用法及代码示例


C# String.Compare() 方法

String.Compare() 方法用于比较两个字符串对象,它根据第一个不同字符的差异返回值 0、小于 0 或大于 0。

用法:

    int String.Compare(String1, String2);

参数:它接受两个字符串进行比较。

返回值:它返回一个int值——可能是 0、小于 0 或大于 0。

例:

    Input:
    string str1 = "IncludeHelp";
    string str2 = "IncludeHelp";
    
    Function call:
    String.Compare(str1, str2)

    Output:
    0

使用 String.Compare() 方法比较两个字符串的 C# 示例

using System;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            //string variables
            string str1 = "IncludeHelp";
            string str2 = "IncludeHelp";

            Console.WriteLine(String.Compare("ABCD", "ABCD"));
            Console.WriteLine(String.Compare("ABCD", "abcd"));
            Console.WriteLine(String.Compare("abcd", "ABCD"));

            //checking the condition
            if (String.Compare(str1, str2)==0)
                Console.WriteLine(str1 + " and " + str2 + " are same");
            else
                Console.WriteLine(str1 + " and " + str2 + " are not same");

            str1 = "INCLUDEHELP";
            str2 = "IncludeHelp";

            if (String.Compare(str1, str2) == 0)
                Console.WriteLine(str1 + " and " + str2 + " are same");
            else
                Console.WriteLine(str1 + " and " + str2 + " are not same");

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

输出

0
1
-1
IncludeHelp and IncludeHelp are same
INCLUDEHELP and IncludeHelp are not same

参考:String.Compare 方法



相关用法


注:本文由纯净天空筛选整理自 String.Compare() method with example in C#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。