C# 字符串处理

1、字符串比较

String.Compare()  比较两个指定System.String对象的子字符串。返回的是整数0,1或-1中的一个整数。

String.CompareOrditional()  通过计算两个System.String对象的每个子字符串中相应System.Char对象的数值比较子字符串。返回整型数据。

CompareTo()  将该实例与指定System.String对象进行比较。返回整型数据。

Equals()  确定该实例是否与指定System.String对象具有相同的值。返回的是Bool型数据。

//字符串的比较

static void Main(string[] args)
        {
            String a = "11111"; 
            String b = "22222"; 
            int i = String.Compare(a, b, true);  //比较2个字符串排序顺序,返回(1、0、-1)。 true为忽略大小写
            switch (i)
            {
                case 1:
                    Console.WriteLine("“{0}”大于“{1}”", a, b);
                    break;
                case 0:
                    Console.WriteLine("“{0}”等于“{1}”", a, b);
                    break;
                case -1:
                    Console.WriteLine("“{0}”小于“{1}”", a, b);
                    break;
            }
            Console.ReadKey();
        }

“11111”小于“22222”

2、字符串的格式化

//字符串的格式化
            float sdr = 0.335555f;
            Console.WriteLine(sdr.ToString("F4")); //保留到小数点后面4位小数,运行结果 0.3356
            Console.WriteLine(sdr.ToString("p"));  //以百分比的形式保存,运行结果 33.56%
            int sdn = 234533;
            Console.WriteLine(sdn.ToString("x"));  //转化为16进制,运行结果 929
            Console.WriteLine(sdn.ToString("E"));  //科学计算法,运行结果 2.4533E+005
            Console.WriteLine(sdn.ToString("c"));  //货币形式,运行结果 ¥234.533.00
            Console.ReadKey();

3、字符串的大小写转换

//字符串的大小写转换
            string s1 = "aaaaa";
            string s2 = "BBBBB";
            Console.WriteLine(s1.ToUpper()); //转化为大写
            Console.WriteLine(s2.ToLower()); //转化为小写
            Console.ReadKey()

4、字符串的拆分与截取

字符串的拆分最常用的方法是Split()方法。截取常用SubString()属性。

//字符串的拆分与截取
            string str = "aaa12,bbb34,ccc56,ddd78";
            string[] shu = str.Split(',');  //这里是单引号,以","为分割符拆分str字符串,并把结果放到字符串数组shu中。
            foreach (string s in shu)
            {
                Console.WriteLine(s); //打印分割后的结果
                Console.WriteLine(s.Substring(0, 3)); //截取字符串的前3位
            }
            Console.ReadKey();
原文地址:https://www.cnblogs.com/han1982/p/2702035.html