[转]字符串和字符数组之间的转换

tepc2000 发表于http://topic.csdn.net/u/20070529/09/36e35c68-f0f2-42ed-89bd-0ac0735438b5.html

字符串和字符数组之间的转换

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

转载于:https://www.cnblogs.com/xjyggd/archive/2008/12/10/1352049.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值