在 C# 中,您可以使用 Compare() 方法來比較兩個字串。此整數值可以小於零、等於零或大於零。如果在給定的兩個字串中,第一個字串按排序順序位於第二個字串之前,則傳回值小於零,且傳回值等於零。如果兩個字串具有相同的值且 Compare() 方法的傳回值大於零;按排序順序,第二個字串位於第一個字串之後。
文法:
文法如下:
String.Compare(string1, string2);
其中 string1 是需要與第二個字串 string2 進行比較的第一個字串。
下面給出的是提到的例子:
C# 程式示範如何使用 Compare() 方法來比較兩個字串。
代碼:
using System; //a class called check is defined public class check { //main method is called within which three string variables are defined to store three different strings public static void Main(string[] args) { string string1 = "Welcome"; string string2 = "to"; string string3 = "C#"; //compare() method is used to compare two strings at a given time which returns an integer value less than zero if the first string precedes the second string in the sorting order or returns an integer value equal to zero if the first string is equal to the second string or returns an integer value greater than zero if the first string is followed by the second string in the sorting order Console.WriteLine("The result of comparing the string1 and string2 is: {0}",string.Compare(string1,string2)); Console.WriteLine("The result of comparing the string2 and string3 is: {0}",string.Compare(string2,string3)); Console.WriteLine("The result of comparing the string3 and string1 is: {0}",string.Compare(string3,string1)); } }
輸出:
說明:
C# 程式示範如何使用 Compare() 方法來比較兩個字串。
代碼:
using System; //a class called check is defined public class check { //main method is called within which three string variables are defined to store three different strings public static void Main(string[] args) { string string1 = "Learning is fun"; string string2 = "Learning is fun"; string string3 = "fun"; //compare() method is used to compare two strings at a given time which returns an integer value less than zero if the first string precedes the second string in the sorting order or returns an integer value equal to zero if the first string is equal to the second string or returns an integer value greater than zero if the first string is followed by the second string in the sorting order Console.WriteLine("The result of comparing the string1 and string2 is: {0}",string.Compare(string1,string2)); Console.WriteLine("The result of comparing the string2 and string3 is: {0}",string.Compare(string2,string3)); Console.WriteLine("The result of comparing the string3 and string1 is: {0}",string.Compare(string3,string1)); } }
輸出:
說明:
以下是優點:
在本教程中,我們透過程式設計範例及其輸出,透過定義、語法和Compare() 方法的工作原理了解了C# 中Compare() 方法的概念,以及在處理問題時在程式中使用Compare( ) 方法的優點帶字串。
以上是C# 比較()的詳細內容。更多資訊請關注PHP中文網其他相關文章!