实用案例,如我想把"Kobe Brynt Lebron James Chris Bosh"这个字符串中的所有空格替换成下划线”_”,该如何处理?
C# 的String为我们提供了一个极好的方法Replace,如下所示。很明显,这是一个重载函数,即可要实现字符替换;还可以实现字符串替换。
public string Replace(char oldChar, char newChar);
public string Replace(string oldValue, string newValue);
- class Program
- {
- static string str1 = "Kobe Brynt Lebron James Chris Bosh";
- static string str2 = string.Empty;
- static void Main(string[] args)
- {
- str2 = str1.Replace(" ", "_");
- Console.WriteLine(" str1={0} \n str2={1}", str1, str2);
- Console.ReadLine();
- }
- }
图1
实际证明,这下面这两句话的效果是一样的。
str2 = str1.Replace(" ", "_");
str2 = str1.Replace(' ', '_');
另外,需要注意的是,Replace返回一个被替换了字符/字符串的拷贝,而它本身并没有被替换。有图有真相,图1.