有没有更好的方法来做到这一点......
MyString.Trim().Replace("&", "and").Replace(",", "").Replace(" ", " ")
.Replace(" ", "-").Replace("'", "").Replace("/", "").ToLower();
Run Code Online (Sandbox Code Playgroud)
我已经扩展了字符串类以使其保持一个工作但是有更快的方法吗?
public static class StringExtension
{
public static string clean(this string s)
{
return s.Replace("&", "and").Replace(",", "").Replace(" ", " ")
.Replace(" ", "-").Replace("'", "").Replace(".", "")
.Replace("eacute;", "é").ToLower();
}
}
Run Code Online (Sandbox Code Playgroud)
只是为了好玩(以及停止评论中的论点),我已经推动了以下各种示例的基准测试.
正则表达式选项得分非常高; 字典选项最快; stringbuilder replace的long winded版本比short hand稍快.
我想知道的是,是否可以替换字符串中的多个字符(例如,&,|和$字符),而不必多次使用.Replace()?目前我正在使用它
return inputData.Replace('$', ' ').Replace('|', ' ').Replace('&', ' ');
Run Code Online (Sandbox Code Playgroud)
但这太可怕了,我想知道是否有类似的小而有效的替代方案.
编辑:谢谢大家的答案,不幸的是,我没有15个声誉需要赞成人
我有一个(大)模板,想要替换多个值。替换需要不区分大小写。还必须能够拥有模板中不存在的键。
例如:
[TestMethod]
public void ReplaceMultipleWithIgnoreCaseText()
{
const string template = "My name is @Name@ and I like to read about @SUBJECT@ on @website@, tag @subject@";
const string expected = "My name is Alex and I like to read about C# on stackoverflow.com, tag C#";
var replaceParameters = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("@name@","Alex"),
new KeyValuePair<string, string>("@subject@","C#"),
new KeyValuePair<string, string>("@website@","stackoverflow.com"),
// Note: The next key does not exist in template
new KeyValuePair<string, string>("@country@","The Netherlands"),
};
var actual = ReplaceMultiple(template, …Run Code Online (Sandbox Code Playgroud) 我知道如何使用以下代码替换段落或文本文件中的另一个特定单词:
String output = input.Replace("oldvalue","newvalue");
Run Code Online (Sandbox Code Playgroud)
但我混淆了更换替换词组.我有近1000个单词要替换.例如:
" aback " => " ashamed ",
" abacus " => " abacus ",
" abaft " => " aback ",
" abandon " => " carelessness ",
" abandoned " => " alone ",
Run Code Online (Sandbox Code Playgroud)
因此,如果段落包含aback我想用ashamed每个单词替换它的单词.我们怎么做?谁能给我一个想法?