C#語言有很多值得學習的地方,這裡我們主要介紹C#字元數群組轉換,包括介紹字串類 System.String 提供了一個 void ToCharArray() 方法等方面。
C#字元數群組轉換
字串類 System.String 提供了一個 void ToCharArray() 方法,該方法可以實現字串到C#字元數群組轉換。如下例:
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");
}
例中以對轉換轉換到的字元數組長度和它的一個元素進行了測試,結果如下:
Length of "mytest" is 6
Length of char array is 6
char[2] = t
可以看出,結果完全正確,這說明轉換成功。那麼反過來,要把C#字元數群組轉換成字串又該如何呢?
我們可以使用 System.String 類的建構函式來解決這個問題。System.String 類有兩個建構函式是通過字元數組來構造的,即 String(char[]) 和 String[char[], int, int)。後者之所以多兩個參數,是因為可以指定用字元數組中的哪一部分來構造字串。而前者則是用字元數組的全部元素來構造字串。我們以前者為例,在 TestStringChars() 函數中輸入如下語句:
char[] tcs = {'t', 'e', 's', 't', ' ', 'm', 'e'};
string tstr = new String(tcs);
this.textBox1.AppendText("tstr = \"" + tstr + "\"\n");
運行結果輸入 tstr = "test me",測試說明轉換成功。
實際上,我們在很多時候需要把字串轉換成字元數組只是為了得到該字串中的某個字元。如果只是為了這個目的,那大可不必興師動眾的去進行轉換,我們只需要使用 System.String 的 [] 運算子就可以達到目的。請看下例,再在 TestStringChars() 函數中加入如如下語名:
char ch = tstr[3];
this.textBox1.AppendText("\"" + tstr + "\"[3] = " + ch.ToString());
正確的輸出是 "test me"[3] = t,經測試,輸出正確。