不可变字符串string的相关操作

        static void Main(string[] args)
        {
            //截取字符串
            string str1 = "ABCDEFGHIJKLMN";
            string str2 = str1.Substring(0, 4);//从0位开始截取,共截取4位;
            Console.WriteLine(str2);
            Console.WriteLine(str2.Substring(0, 2));
            Console.ReadKey();

            //分割字符串
            string strA = "AI时代已经到来,请做好准备;";
            char[] separator = { ',' }; //分割字符,数据类型必须是字符类型数组;
            string[] strB = new string[100];
            strB = strA.Split(separator);
            for (int i = 0; i < strB.Length; i++)
            {
                Console.WriteLine(strB[i]);
            }
            Console.ReadLine();

            //插入字符串
            string strC = "a12345";
            string strD = strC.Insert(1, "999");
            Console.WriteLine(strD);
            Console.ReadKey();

            //填充字符串(左填充和右填充)
            string strE = "sdf";
            string strF = strE.PadLeft(5, 'A');
            string strG = strF.PadRight(7, 'A');
            Console.WriteLine(strF);
            Console.WriteLine(strG);
            Console.ReadLine();

            //删除字符串
            string strH = "sdfsag";
            string strI = strH.Remove(1, 2);
            Console.WriteLine(strI);
            Console.ReadKey();

            //复制字符串Copy()和CopyTo()
            string str11 = "123";
            char[] char1 = new char[100];
            string str22 = string.Copy(str11);
            str11.CopyTo(0, char1, 0, 3);//待复制字符起始位置,目标字符数组,目标数组起始存放位置,数量;
            Console.WriteLine(str22);
            for (int i = 0; i < str11.Length; i++)
            {
                Console.WriteLine(char1[i]);
            }
            Console.ReadLine();

            //替换字符串
            string str33 = "abcabc";
            string str55 = str33.Replace('a', 'd');//字符'd'替换字符'a'
            string str66 = str33.Replace("abc", "def");//字符串"def"替换字符串"abc";
            Console.WriteLine(str55);
            Console.WriteLine(str66);
            Console.ReadLine();

        }

 

posted @ 2024-08-18 17:29  CSF践行  阅读(4)  评论(0编辑  收藏  举报