且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C# String.Replace

更新时间:2022-08-31 13:42:08

    实用案例,如我想把"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. }


 

C# String.Replace

图1

 

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

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

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

 

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