相关疑难解决方法(0)

在C#中替换多个字符串元素

有没有更好的方法来做到这一点......

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)

只是为了好玩(以及停止评论中的论点),我已经推动了以下各种示例的基准测试.

https://gist.github.com/ChrisMcKee/5937656

正则表达式选项得分非常高; 字典选项最快; stringbuilder replace的long winded版本比short hand稍快.

c# string refactoring immutability

77
推荐指数
5
解决办法
9万
查看次数

用一个衬里替换c#中字符串中的多个字符

我想知道的是,是否可以替换字符串中的多个字符(例如,&,|和$字符),而不必多次使用.Replace()?目前我正在使用它

return inputData.Replace('$', ' ').Replace('|', ' ').Replace('&', ' ');
Run Code Online (Sandbox Code Playgroud)

但这太可怕了,我想知道是否有类似的小而有效的替代方案.

编辑:谢谢大家的答案,不幸的是,我没有15个声誉需要赞成人

.net c# replace

16
推荐指数
2
解决办法
3万
查看次数

如何使用 StringBuilder 进行多个不区分大小写的替换

我有一个(大)模板,想要替换多个值。替换需要不区分大小写。还必须能够拥有模板中不存在的键。

例如:

[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)

c# stringbuilder

3
推荐指数
1
解决办法
3342
查看次数

用另一个替换单词集

我知道如何使用以下代码替换段落或文本文件中的另一个特定单词:

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每个单词替换它的单词.我们怎么做?谁能给我一个想法?

c# replace

-1
推荐指数
1
解决办法
1227
查看次数

标签 统计

c# ×4

replace ×2

.net ×1

immutability ×1

refactoring ×1

string ×1

stringbuilder ×1