【简 介】 C# 出来也有些日子了,最近由于编程的需要,对 C# 的类型转换做了一些研究,其内容涉及 C# 的装箱/拆箱/别名、数值类型间相互转换、字符的 ASCII 码和 Unicode 码、数值字符串和数值之间的转换、字符串和字符数组/字节数组之间的转换、各种数值类型和字节数组之间的转换、十六进制数输出以及日期型数据的一些转换处理 |
|
|
|
|
private void TestStringValue() { float f = 54.321F; string str = "123"; this.textBox1.Text = ""; this.textBox1.AppendText("f = " + f.ToString() + "\n"); if (int.Parse(str) == 123) { this.textBox1.AppendText("str convert to int successfully."); } else { this.textBox1.AppendText("str convert to int failed."); }}
运行结果:
f = 54.321
str convert to int successfully.
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,经测试,输出正确。
|
|
|
|
|
| 杀毒软件免费随便用
瑞星全功能安全软件2009 基于“云安全”策略和“智能主动防御”技术开发.
www.rising.com.cn
|
|
|
|