C# 中的類型轉換之字串和字元數組之間的轉換

來源:互聯網
上載者:User
C# 中的類型轉換之字串和字元數組之間的轉換(轉) =========================================================== 作者: hphubei(http://hphubei.itpub.net)
發表於: 2007.07.06 18:32
分類: ASP.NET技巧
出處: http://hphubei.itpub.net/post/2868/304735
--------------------------------------------------------------- 5. 字串和字元數組之間的轉換

字串類 System.String 提供了一個 void ToCharArray() 方法,該方法可以實現字串到字元數組的轉換。如下例:

private void TestStringChars() {

string str = "mytest";

char[] chars = str.ToCharArray();

this.textBox1.Text = "";

this.textBox1.AppendText("Length of "mytest" is " + str.Length + " ");

this.textBox1.AppendText("Length of char array is " + chars.Length + " ");

this.textBox1.AppendText("char[2] = " + chars[2] + " ");

}

例中以對轉換轉換到的字元數組長度和它的一個元素進行了測試,結果如下:

Length of "mytest" is 6

Length of char array is 6

char[2] = t

可以看出,結果完全正確,這說明轉換成功。那麼反過來,要把字元數群組轉換成字串又該如何呢?

我們可以使用 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 + "" ");

運行結果輸入 tstr = "test me",測試說明轉換成功。

實際上,我們在很多時候需要把字串轉換成字元數組只是為了得到該字串中的某個字元。如果只是為了這個目的,那大可不必興師動眾的去進行轉換,我們只需要使用 System.String 的 [] 運算子就可以達到目的。請看下例,再在 TestStringChars() 函數中加入如如下語名:

char ch = tstr[3];

this.textBox1.AppendText(""" + tstr + ""[3] = " + ch.ToString());

正確的輸出是 "test me"[3] = t,經測試,輸出正確。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.