验证C#中String.Insert方法

前几天在面试中碰到一个看似不起眼却没怎么用过的一个方法: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这个方法是直接插入不是替换掉原来的相应位置字符。

转载于:https://www.cnblogs.com/2012-10-3/articles/3819837.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值