C#常用字符串总结

  1. 字符串基础《一》
static void Main(string[] args)
        {
            string str1 = "I Love You";
            string str2 = "这里是北京";
            string[] strArr = {"A","B","C","D","E","F" };
            char[] chr = { '1', '2', '3', '4', '5', '6' };

            string newValue = new string(chr); // 灵活将char数组组合成一个字符串:"123456"

            Console.WriteLine(newValue);

            newValue = new string('a', 2);  //重复输出前面的char字符,得到一个新的字符串:"aa"

            Console.WriteLine(newValue);

            int comNum = string.Compare(str1, str2);
            //如果str1 > str2 则返回1,否则返回 -1;等于返回0

            Console.WriteLine(comNum);

            newValue = string.Concat(str1, str2); //将两个字符串连接起来,组成新字符串
            Console.WriteLine(newValue);

           newValue = string.Format("{0}-{1}", str1,str2,chr[0]); //格式化输出,注意前面的占位符智能小于或等于后面的值

            Console.WriteLine(newValue);

            newValue = string.Join(",,", strArr);  //用两个逗号将字符串数组,组成新的字符串输出

            Console.WriteLine(newValue);

            bool isStrNull = string.IsNullOrEmpty(str1);  //判断字符串是否为空,不为空返回False,为空返回True
            Console.WriteLine(isStrNull);

2、字符串基础《二》

  string strVal = "我是一名程序员";
            strVal = strVal.Replace("", ""); //用后面的字符替换前面的
            Console.WriteLine(strVal);
            strVal = strVal.Remove(2, 2);  //从索引为2的位置删除两个字符
            Console.WriteLine(strVal);
            strVal = strVal.Substring(2, 2); //从索引为2的位置截取两个字符串返回
            Console.WriteLine(strVal);

            char[] c = strVal.ToCharArray(); //字符串转换成char数组
            Console.WriteLine(c);
           char[] cc = chr.ToArray();

           bool isContain = strVal.Contains("程序"); //查找是否包含程序两个字

           int v = strVal.IndexOf("程序1", 1);  //从索引为1的位置开始,查找程序,如果找到返回索引所在位置,如果没有返回-1
            Console.WriteLine(v);

        char[] ch = { '程', '员' };
        strVal = "我是一名程序员";
        int vNum = strVal.IndexOfAny(ch); //返回ch数组中,第一个匹配成功的字符索引位置:4

 

        bool isS = strVal.StartsWith("我");  //判断是否以我开头,如果是返回true,否则返回false

 str =  strVal.Split(ch, StringSplitOptions.RemoveEmptyEntries); //按char数组中字符,分别去拆分字符串,只要符合char数组某元素就拆分
例子如下:
  string strV = "I Love    Bei  Jing";
  string[] s = strV.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
//返回没有空格的数组,长度位4

 

posted @ 2019-03-31 19:00  Micc_it  阅读(379)  评论(0)    收藏  举报