字符串快速替换 解决方案

如题: string test="abcdefgcd";

现在要将第一个c 替换成mmm  (当然这里肯定是指定具体位置)

如何才能快速替换,谁帮忙写个封装的方法


波斯汪
浏览 396回答 1
1回答

慕尼黑5688855

static string ReplaceString(string oldstr, string filterstring,string newstring) &nbsp; &nbsp; &nbsp; &nbsp;{ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;string result = string.Empty; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (string.IsNullOrEmpty(oldstr) || string.IsNullOrEmpty(filterstring) ||newstring==null) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return result; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;int position = oldstr.IndexOf(filterstring); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (position <= 0) { return result; } &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//first position &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;string beginstr = oldstr.Substring(0, position + filterstring.Length); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;string endstr=oldstr.Substring(position+filterstring.Length); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;beginstr = beginstr.Replace(filterstring, newstring); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;result = beginstr + endstr; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return result; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp;string test="abccdefgccd"; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.WriteLine(ReplaceString(test, "cc", "mmm"));&nbsp;结果:abmmmdefgccd
打开App,查看更多内容
随时随地看视频慕课网APP