标签:修改 [] string类 第一个 png space 元素 tty nbsp



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);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();}}}

标签:修改 [] string类 第一个 png space 元素 tty nbsp
原文地址:http://www.cnblogs.com/HelloZyjS/p/6032502.html