Chinaunix首页 | 论坛 | 博客
  • 博客访问: 654411
  • 博文数量: 111
  • 博客积分: 5010
  • 博客等级: 大校
  • 技术积分: 1461
  • 用 户 组: 普通用户
  • 注册时间: 2008-01-08 14:40
文章分类

全部博文(111)

文章存档

2010年(10)

2009年(70)

2008年(31)

我的朋友

分类: C/C++

2009-12-09 10:28:11

  这里介绍我们可以使用 System.String 类的构造函数来解决这个问题。System.String 类有两个构造函数是通过字符数组来构造的,即 String(char[]) 和 String[char[], int, int)。

  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,经测试,输出正确。

阅读(1164) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~