前几天在面试中碰到一个看似不起眼却没怎么用过的一个方法:string.Insert(int startIndex,string value),作用是在原来字符串的基础上在指定位置上插入想要插入的字符串后得到一个新的字符串。
就两个参数,也没有重载方法。顾名思义,第一个参数为要插入的开始位置,潜在的异常是此参数的值为负数;第二个参数是要插入的值,潜在的异常是这个值为空。
看代码:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 6 string old = "abcdefg";//原始字符串 7 string insert = "fff";//要插入的字符串 8 string wartch_old = old;//查看原来的字符串变化 9 old = old.Insert(1, insert); 10 string wartch_old2 = old;//查看第一次插入后的old的变化 11 old = old.Insert(0, insert); 12 13 14 Console.WriteLine(old); 15 Console.WriteLine(wartch_old); 16 Console.WriteLine(wartch_old2); 17 Console.ReadLine(); 18 } 19 }
输出结果:
从输出可以验证了一个string的特征,不可变性。每次对申明的字符串执行操作都是重新开辟一个新的返回。另外也证明,Insert这个方法是直接插入不是替换掉原来的相应位置字符。