當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。