Chinaunix首页 | 论坛 | 博客
  • 博客访问: 12400849
  • 博文数量: 1293
  • 博客积分: 13501
  • 博客等级: 上将
  • 技术积分: 17974
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-08 18:11
文章分类

全部博文(1293)

文章存档

2019年(1)

2018年(1)

2016年(118)

2015年(257)

2014年(128)

2013年(222)

2012年(229)

2011年(337)

分类: C#/.net

2013-11-21 16:51:51

    实用案例,如我想把"Kobe Brynt Lebron James Chris Bosh"这个字符串中的所有空格替换成下划线”_”,该如何处理?

    C# 的String为我们提供了一个极好的方法Replace,如下所示。很明显,这是一个重载函数,即可要实现字符替换;还可以实现字符串替换。

    public string Replace(char oldChar, char newChar);

    public string Replace(string oldValue, string newValue);


  1. class Program
  2. {
  3.     static string str1 = "Kobe Brynt Lebron James Chris Bosh";
  4.     static string str2 = string.Empty;
  5.     static void Main(string[] args)
  6.     {
  7.         str2 = str1.Replace(" ", "_");
  8.         Console.WriteLine(" str1={0} \n str2={1}", str1, str2);
  9.         Console.ReadLine();
  10.     }
  11. }


 

image

图1

 

    实际证明,这下面这两句话的效果是一样的。

str2 = str1.Replace(" ", "_");

str2 = str1.Replace(' ', '_');

 

    另外,需要注意的是,Replace返回一个被替换了字符/字符串的拷贝,而它本身并没有被替换。有图有真相,图1.

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