using System.Text;  //使用StringBuilder需要
using System.IO;    //使用StringReaderStringBuilder
先從StringBuilder開始介紹吧
StringBuilder組要拿來做字串的串接,
網路上查詢了一下,
網路表示:
當串接的字串過多時,
使用StringBuilder的效能較好,
範例大多都是for迴圈跑個幾千幾萬筆做測試,
而當字串資料量小時其實使用"+"將字串串接效能反而比較好,
目前想到的應用,
大概就是讀入了一篇文章,
需要將文章部份特殊字元做處理(如\n、\u等等),
需要直個字元單一讀入並處理,
這時使用StringBuilder效果應該就不錯!
部分程式碼:
string StringBuilderTest()
{
    StringBuilder str = new StringBuilder();
    str.Append("hello");
    str.Append(" ");
    str.Append("world!");
    return str.ToString();
}hello world!
//----------
StringReader
1. ReadToEnd() //將字串全部讀完
部分程式碼:
void StringReaderTest()
{
    string s ="hi,\n,read to end!\nfinish";
    StringReader sr = new StringReader(s);
    Debug.Log(sr.ReadToEnd());
}hihi,
my name is wilson,
nice to meet you!
//--------
2. ReadLine() //一次讀一行測試
部分程式碼:
void StringReaderTest()
{
    string s ="hihi,\nmy name is wilson,\nnice to need you!";
    StringReader sr = new StringReader(s);
    while(true){
        if(sr.Peek() ==-1)  //判斷下一個讀取是否還有值
            break;
        Debug.Log(sr.ReadLine()); //一次一行
    }
}hihi,
my name is wilson,
nice to meet you!
//--------
3. Read() //逐字元讀
部分程式碼:
void StringReaderTest()
{
    string s ="abc de";
    StringReader sr = new StringReader(s);
    while(true){
        if(sr.Peek() ==-1)
            break;
        char c = System.Convert.ToChar(sr.Read()); //一次一個
        Debug.Log(c.ToString());
    }
}a
b
c
d
e
//--------
4. ReadBlock(儲存字元陣列,idx,讀取字串長度) //讀取字元,並於字元陣列idx處開始存入字元
部分程式碼:
void StringReadBlockTest()
{
    string s ="abc de";
    StringReader sr = new StringReader(s);
  
    char[] cb = new char[s.Length-1];
    sr.ReadBlock(cb,1,cb.Length-1);
    for(int i =0;i<cb.Length;i++)
        Debug.Log("char is :"+cb[i].ToString());
}char is : //因為idx = 1 ,故第cb[0]為空字元
char is :a
char is :b
char is :c
char is :
//
 
沒有留言:
張貼留言