

namespace _07.字符串的第二个特性{ class Program { static void Main(string[] args) { //可以将string类型看成char类型的一个只读数组 string s = "abcdefg"; //既然可以将string看做char类型的只读数组,所以我们可以通过下标去访问字符串中的某一个元素 char c1 = s[0]; Console.WriteLine(c1); //获得了a //s[0] = ‘b‘; 不能这样做因为是只读的 //如果我们非要改变第一个元素的值为‘b‘怎么办呢? //首先我们要将字符串转换成char数组 char[] c2 = new char[s.Length]; for (int i = 0; i < s.Length; i++) { c2[i] = s[i]; } //然后我们再修改第一个元素 c2[0] = ‘b‘; //最后我们在将这个字符数组转换成字符串 //string s2 = ""; 频繁的给一个字符串变量赋值由于字符串的不可变性,会产生大量的内存垃圾 StringBuilder s2=new StringBuilder(); //使用StringBuilder频繁的接受赋值就不会产生垃圾 for (int i = 0; i < c2.Length; i++) { s2.Append(c2[i]); } string s3 = s2.ToString(); //最后再转换成string类型 Console.WriteLine(s3);
//当然也可以用ToCharArray()方法转换
// char[] chs = s.ToCharArray();
//Console.ReadLine(chs);
Console.ReadKey(); } }}
namespace _08.StringBuilder的使用{ class Program { static void Main(string[] args) { string str = null; Stopwatch sw = new Stopwatch(); //用来测试代码执行的时间 sw.Start(); //开始计时 for (int i = 0; i < 100000; i++) { str += i; } sw.Stop(); Console.WriteLine(str); Console.WriteLine(sw.Elapsed); //获取代码运行的时间 Console.ReadKey(); } }}
大约有14秒namespace _08.StringBuilder的使用{ class Program { static void Main(string[] args) { string str = null; StringBuilder sb = new StringBuilder(); Stopwatch sw = new Stopwatch(); //用来测试代码执行的时间 sw.Start(); //开始计时 for (int i = 0; i < 100000; i++) { sb.Append(i); } sw.Stop(); str = sb.ToString(); Console.WriteLine(str); Console.WriteLine(sw.Elapsed); //获取代码运行的时间 Console.ReadKey(); } }}
原文:http://www.cnblogs.com/hao-1234-1234/p/6119801.html