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 方法
相關用法
- C# String.Copy()用法及代碼示例
- C# String.Contains()用法及代碼示例
- C# String.CopyTo()用法及代碼示例
- C# String.Clone()用法及代碼示例
- C# String.ToUpperInvariant用法及代碼示例
- C# String.ToLowerInvariant用法及代碼示例
- C# String.IsNullOrEmpty()用法及代碼示例
- C# String.ToCharArray()用法及代碼示例
- C# String.Insert()用法及代碼示例
- C# String.Split()用法及代碼示例
- C# String.Format()函數用法及代碼示例
- C# String.Format()方法用法及代碼示例
- C# String.IsNormalized用法及代碼示例
- C# String.IndexOf()方法用法及代碼示例
- C# StringBuilder.ToString用法及代碼示例
- C# String ToLower()用法及代碼示例
- C# String ToString()用法及代碼示例
- C# String Contains()用法及代碼示例
- C# String ToCharArray()用法及代碼示例
- C# String IndexOf()用法及代碼示例
注:本文由純淨天空篩選整理自 String.Compare() method with example in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。