C#字符數(shù)組轉(zhuǎn)換剖析
C#語言有很多值得學(xué)習(xí)的地方,這里我們主要介紹C#字符數(shù)組轉(zhuǎn)換,包括介紹字符串類 System.String 提供了一個(gè) void ToCharArray() 方法等方面。
C#字符數(shù)組轉(zhuǎn)換
字符串類 System.String 提供了一個(gè) void ToCharArray() 方法,該方法可以實(shí)現(xiàn)字符串到C#字符數(shù)組轉(zhuǎn)換。如下例:
- private void TestStringChars() {
- string str = "mytest";
- char[] chars = str.ToCharArray();
- this.textBox1.Text = "";
- this.textBox1.AppendText("Length of \"mytest\" is " + str.Length + "\n");
- this.textBox1.AppendText("Length of char array is " + chars.Length + "\n");
- this.textBox1.AppendText("char[2] = " + chars[2] + "\n");
- }
例中以對轉(zhuǎn)換轉(zhuǎn)換到的字符數(shù)組長度和它的一個(gè)元素進(jìn)行了測試,結(jié)果如下:
- Length of "mytest" is 6
- Length of char array is 6
- char[2] = t
可以看出,結(jié)果完全正確,這說明轉(zhuǎn)換成功。那么反過來,要把C#字符數(shù)組轉(zhuǎn)換成字符串又該如何呢?
我們可以使用 System.String 類的構(gòu)造函數(shù)來解決這個(gè)問題。System.String 類有兩個(gè)構(gòu)造函數(shù)是通過字符數(shù)組來構(gòu)造的,即 String(char[]) 和 String[char[], int, int)。后者之所以多兩個(gè)參數(shù),是因?yàn)榭梢灾付ㄓ米址麛?shù)組中的哪一部分來構(gòu)造字符串。而前者則是用字符數(shù)組的全部元素來構(gòu)造字符串。我們以前者為例,在 TestStringChars() 函數(shù)中輸入如下語句:
- char[] tcs = {'t', 'e', 's', 't', ' ', 'm', 'e'};
- string tstr = new String(tcs);
- this.textBox1.AppendText("tstr = \"" + tstr + "\"\n");
運(yùn)行結(jié)果輸入 tstr = "test me",測試說明轉(zhuǎn)換成功。
實(shí)際上,我們在很多時(shí)候需要把字符串轉(zhuǎn)換成字符數(shù)組只是為了得到該字符串中的某個(gè)字符。如果只是為了這個(gè)目的,那大可不必興師動(dòng)眾的去進(jìn)行轉(zhuǎn)換,我們只需要使用 System.String 的 [] 運(yùn)算符就可以達(dá)到目的。請看下例,再在 TestStringChars() 函數(shù)中加入如如下語名:
- char ch = tstr[3];
- this.textBox1.AppendText("\"" + tstr + "\"[3] = " + ch.ToString());
正確的輸出是 "test me"[3] = t,經(jīng)測試,輸出正確。
【編輯推薦】