在 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中文网其他相关文章!