在c#的字符串操作过程中,有时候需要替换字符串中的某个子字符串,此时就可以使用到字符串类自带的replace方法来实现,replace方法将查找到所有符合被替换的子字符串,然后将之全部替换为目标字符串。replace方法有2个方法重载实现,一个是string replace(string oldvalue, string newvalue),另一个是replace(char oldchar, char newchar);前面的那个重载形式为以子字符串的形式来进行替换,而后面的重载形式为按照单个字符匹配进行替换。

例如字符串string str=”hello  world”;

(1)将子字符串hello 替换为ni hao。

string str = “hello world”;

string resulta = str.replace(“hello”, “ni hao”);

(2)将字符串中所有的o字符替换为a,下面2中方法都可以。

string str = “hello world”;

string resultb = str.replace(“o”, “a”);
string resultc = str.replace(‘o’, ‘a’);

备注:原文转载自博主个人站it技术小趣屋,原文链接c#中string类使用replace方法来替换字符串_it技术小趣屋。