字符串常用处理


            //字符串
            string strTest = "123stre汉字";

            //insert 在索引位置前面插入
            Console.WriteLine(strTest.Insert(1, "5"));

            //remove 删除从指定索引开始的指定个数的字符串
            Console.WriteLine(strTest.Remove(3, 3));

            //replace 当没有匹配时,返回本身字符串
            Console.WriteLine(strTest.Replace("1234", "456"));

            //length 长度:一个汉字按一个算
            Console.WriteLine(strTest.Length);
           
       
            //substring 从某个索引开始(包含开始字符)的指定长度的字符串;超过报错异常
            Console.WriteLine(strTest.Substring(1, 3));
            Console.WriteLine(strTest.Substring(4));

         

            //IndexOf 当不存在时,返回-1;否则,返回索引位置(从0开始)
            Console.WriteLine("indexof:  "+strTest.IndexOf("123"));
            Console.WriteLine("indexof:  "+strTest.LastIndexOf("123"));

          

            //Contains
            Console.WriteLine(strTest.Contains("34"));


            //split 当没有匹配项时,返回整个字符串
            string[] strArr = strTest.Split('4');
            foreach (string item in strArr)
                Console.WriteLine(item);
          
            //ToCharArray
            char[] charArr = strTest.ToCharArray(0, 4);
            foreach(char item in charArr)
            Console.WriteLine(item);


            Console.WriteLine(strTest.Clone());//返回字符串本身

            //copyto 字符串拷贝替换: 源字符串指定索引开始的字符串 替换掉 目标字符串的指定索引开始的字符
            char[]  charCopy={'4','6'};
            strTest.CopyTo(0, charCopy, 0, 1);
            Console.WriteLine(charCopy);
          
            //copareTo 不一致的话就返回-1;一致返回0
            Console.WriteLine(strTest.CompareTo("123stre汉字"));

            //
            Console.WriteLine(string.Compare(strTest, "123stre汉字", false));

            //string
            //Concat
            Console.WriteLine( string.Concat(strTest,"55"));

            Console.WriteLine(string.Format("{0}",strTest));

            Console.WriteLine(string.IsNullOrEmpty(""));

            //join 在数组元素间串联分割符,返回字符串;
            string[] tmpStr = { "abc", "def", "ghi" };
            string jn = string.Join("-", tmpStr);
            Console.WriteLine(jn);

你可能感兴趣的:(字符串)