C#学习记录1-Compare
在C#中的Compare----比较两个指定的 string 对象,并返回一个表示它们在排列顺序中相对位置的整数。该方法区分大小写。
Compare的表示方式有两种
第一种方法:String.Compare(str1,str2)
返回值:
1 : str1大于str2
0 : str1等于str2
-1 : str1小于str2
例如:
String fname,lname; fname="sssss"; lname="mmmm"; Console.WriteLine(String.Compare(fname, lname));
返回结果为:
第二种方法:public static int Compare( string strA, string strB )
例如:
public static bool Compare( string str1, string str2 ){ //string.IsNullOrWhiteSpace(str1) 指示指定的字符串是 null、空还是仅由空白字符组成。 if (string.IsNullOrWhiteSpace(str1) || string.IsNullOrWhiteSpace(str2)) return false; int n = str1.Length < str2.Length ? str1.Length : str2.Length; // x?y:z 表示如果表达式x为true,则返回y;如果x为false,则返回z for (int i = 0; i < n; i++) { if (str1[i] > str2[i]) return true; else if (str1[i] < str2[i]) return false; else continue; } if (str1.Length > str2.Length) return true; else return false; } static void Main(string[] args) { string strB="asd"; string strA="zxc"; Console.WriteLine(Program.Compare(strA,strB)); }
返回结果为:
————————————————————-
注:C #,不像VB.NET和java,你不能访问静态成员和实例的语法。
错误写法:
class Program{ public static int Compare( string strA, string strB ){ } static void Main(string[] args){ Program a=new Program(); Console.WriteLine(a.Compare(strA,strB)); } }
改为:
Console.WriteLine(Program.Compare(strA,strB));