C# 替代多个 String.Replaces
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12007358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Alternative to multiple String.Replaces
提问by Petter Brodin
My code uses String.Replaceseveral times in a row:
我的代码String.Replace连续使用了几次:
mystring = mystring.Replace("somestring", variable1);
mystring = mystring.Replace("somestring2", variable2);
mystring = mystring.Replace("somestring3", variable1);
I suspect there's a better and faster way to do it. What would you suggest?
我怀疑有更好更快的方法来做到这一点。你有什么建议?
采纳答案by Rostov
For an 'easy' alternative just use a StringBuilder....
对于“简单”的替代方案,只需使用 StringBuilder ....
StringBuilder sb = new StringBuilder("11223344");
string myString =
sb
.Replace("1", string.Empty)
.Replace("2", string.Empty)
.Replace("3", string.Empty)
.ToString();
回答by Daniel Hilgarth
You could at least chain the statements:
您至少可以链接以下语句:
mystring = mystring.Replace("somestring", variable1)
.Replace("somestring2", variable2)
.Replace("somestring3", variable3);
回答by Matt Razza
Depending how your data is organized (what you're replacing) or how many you have; an array and loops might be a good approach.
取决于您的数据的组织方式(您要替换的内容)或您拥有的数据数量;数组和循环可能是一个好方法。
string[] replaceThese = {"1", "2", "3"};
string data = "replace1allthe2numbers3";
foreach (string curr in replaceThese)
{
data = data.Replace(curr, string.Empty);
}
回答by Jamiec
Are we going for ways to make this harderto understand what is going on?
我们是否正在寻找使这更难理解发生了什么的方法?
If so regex is your friend
如果是这样,正则表达式是你的朋友
var replacements = new Dictionary<string,string>()
{
{"somestring",someVariable1},
{"anotherstring",someVariable2}
};
var regex = new Regex(String.Join("|",replacements.Keys.Select(k => Regex.Escape(k))));
var replaced = regex.Replace(input,m => replacements[m.Value]);
回答by Jonathan Prates
This article Regex: replace multiple strings in a single pass with C#can be helpful:
这篇文章正则表达式:用 C# 替换单次传递中的多个字符串可能会有所帮助:
static string MultipleReplace(string text, Dictionary replacements) {
return Regex.Replace(text,
"(" + String.Join("|", adict.Keys.ToArray()) + ")",
delegate(Match m) { return replacements[m.Value]; }
);
}
// somewhere else in code
string temp = "Jonathan Smith is a developer";
adict.Add("Jonathan", "David");
adict.Add("Smith", "Seruyange");
string rep = MultipleReplace(temp, adict);
回答by 4444
Calling Replacethree times is not only a valid answer, it might be the preferred one:
打电话Replace三遍不仅是一个有效的答案,它可能是首选的答案:
RegEx takes three steps: Parse, Execute, Formulate. But String.Replaceis hard-coded, so in many cases it has superior speed. And a complex RegEx isn't as readable as a well-formatted chain of Replacestatements. (Compare Jonathan's solution to Daniel's)
RegEx 需要三个步骤:解析、执行、公式化。但是String.Replace是硬编码的,因此在许多情况下它具有卓越的速度。并且复杂的 RegEx 不如格式良好的Replace语句链可读。(将Jonathan的解决方案与Daniel的解决方案进行比较)
If you're still not convinced that Replaceis better for your case, make a competition out of it! Try both methods side-by-side and use a Stopwatchto see how many milliseconds you save when using your data.
如果您仍然不相信这Replace对您的情况更好,请与之竞争!并排尝试这两种方法,并使用 aStopwatch来查看使用数据时节省了多少毫秒。
But DON'Toptimize your code unless you need to!Any developer will prefer readability and maintainability over a cryptic pile of spaghetti that performs 3 milliseconds faster.
但是除非您需要,否则不要优化您的代码!任何开发人员都会更喜欢可读性和可维护性,而不是一堆执行速度快 3 毫秒的神秘意大利面。
回答by Isaac Baker
My preferred method is to use the power of Regexto solve a multiple replace problem. The only issue with this approach is you only get to choose one stringto replace with.
我的首选方法是使用 的力量Regex来解决多重替换问题。这种方法的唯一问题是您只能选择一个string来替换。
The following will replace all '/'or ':'with a '-'to make a valid file name.
以下将替换 all'/'或':'a'-'以生成有效的文件名。
Regex.Replace("invalid:file/name.txt", @"[/:]", "-");
回答by mathijsuitmegen
If you don't want to use RegEx add this class to your project,
It uses an extension method 'MultipleReplace':
如果您不想使用 RegEx 将此类添加到您的项目中,
它使用扩展方法“MultipleReplace”:
public static class StringExtender
{
public static string MultipleReplace(this string text, Dictionary<string, string> replacements)
{
string retVal = text;
foreach (string textToReplace in replacements.Keys)
{
retVal = retVal.Replace(textToReplace, replacements[textToReplace]);
}
return retVal;
}
}
Then you can use this piece of code:
然后你可以使用这段代码:
string mystring = "foobar";
Dictionary<string, string> stringsToReplace = new Dictionary<string,string>();
stringsToReplace.Add("somestring", variable1);
stringsToReplace.Add("somestring2", variable2);
stringsToReplace.Add("somestring3", variable1);
mystring = mystring.MultipleReplace(stringsToReplace);

