采飞扬的小屋

导航

C# .Net中的类型转换(3)

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 + "\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

可以看出,结果完全正确,这说明转换成功。那么反过来,要把字符数组转换成字符串又该如何呢?

我们可以使用 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,经测试,输出正确。

6. 字符串和字节数组之间的转换

如果还想从 System.String 类中找到方法进行字符串和字节数组之间的转换,恐怕你会失望了。为了进行这样的转换,我们不得不借助另一个类:System.Text.Encoding。该类提供了 bye[] GetBytes(string) 方法将字符串转换成字节数组,还提供了 string GetString(byte[]) 方法将字节数组转换成字符串。

System.Text.Encoding 类似乎没有可用的构造函数,但我们可以找到几个默认的 Encoding,即 Encoding.Default(获取系统的当前 ANSI 代码页的编码)、Encoding.ASCII(获取 7 位 ASCII 字符集的编码)、Encoding.Unicode(获取采用 Little-Endian 字节顺序的 Unicode 格式的编码)、Encoding.UTF7(获取 UTF-7 格式的编码)、Encoding.UTF8(获取 UTF-8 格式的编码) 等。这里主要说说 Encoding.Default 和 Encoding.Unicode 用于转换的区别。

在字符串转换到字节数组的过程中,Encoding.Default 会将每个单字节字符,如半角英文,转换成 1 个字节,而把每个双字节字符,如汉字,转换成 2 个字节。而 Encoding.Unicode 则会将它们都转换成两个字节。我们可以通过下列简单的了解一下转换的方法,以及使用 Encoding.Default 和 Encodeing.Unicode 的区别:

private void TestStringBytes() {
string s = "C#语言";
byte[] b1 = System.Text.Encoding.Default.GetBytes(s);
byte[] b2 = System.Text.Encoding.Unicode.GetBytes(s);
string t1 = "", t2 = "";
foreach (byte b in b1) {
t1 += b.ToString("") + " ";
}
foreach (byte b in b2) {
t2 += b.ToString("") + " ";
}
this.textBox1.Text = "";
this.textBox1.AppendText("b1.Length = " + b1.Length + "\n");
this.textBox1.AppendText(t1 + "\n");
this.textBox1.AppendText("b2.Length = " + b2.Length + "\n");
this.textBox1.AppendText(t2 + "\n");
}

运行结果如下,不说详述,相信大家已经明白了。

b1.Length = 6

67 35 211 239 209 212

b2.Length = 8

67 0 35 0 237 139 0 138

将字节数组转换成字符串,使用 Encoding 类的 string GetString(byte[]) 或 string GetString(byte[], int, int) 方法,具体使用何种 Encoding 还是由编码决定。在 TestStringBytes() 函数中添加如下语句作为实例:

byte[] bs = {97, 98, 99, 100, 101, 102};

string ss = System.Text.Encoding.ASCII.GetString(bs);

this.textBox1.AppendText("The string is: " + ss + "\n");

运行结果为:The string is: abcdef

posted on 2007-05-07 21:46  采飞扬  阅读(96)  评论(0编辑  收藏  举报