C# 中的类型转换之字符串和字符数组之间的转换

来源:互联网 发布:安卓破解软件 编辑:程序博客网 时间:2024/05/04 13:39
C# 中的类型转换之字符串和字符数组之间的转换(转)
===========================================================
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,经测试,输出正确。

原创粉丝点击