用单行替换 c# 中字符串中的多个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17941399/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:52:54  来源:igfitidea点击:

Replacing multiple characters in a string in c# by a one liner

c#.netreplace

提问by user2629770

What I'm wondering of is whether it is possible to replace multiple characters in a string (lets say, the &, | and $ characters for example) without having to use .Replace() several times ? Currently I'm using it as

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

return inputData.Replace('$', ' ').Replace('|', ' ').Replace('&', ' ');

but that is just awful and I'm wondering if a similarly small, yet effective alternative is out there.

但这太糟糕了,我想知道是否有类似的小而有效的替代方案。

EDIT: Thanks everyone for the answers, unfortunately I don't have the 15 reputation needed to upvote people

编辑:感谢大家的回答,不幸的是,我没有 15 名声望来支持人们

采纳答案by MarcinJuraszek

You can use Regex.Replace:

您可以使用Regex.Replace

string output = Regex.Replace(input, "[$|&]", " ");

回答by Maxim Zhukov

You can use Splitfunction and String.Joinnext:

您可以使用Split功能和String.Join下一步:

String.Join(" ", abc.Split('&', '|', '$'))

Test code:

测试代码:

static void Main(string[] args)
{
     String abc = "asdfj$asdfj$sdfjn&sfnjdf|jnsdf|";
     Console.WriteLine(String.Join(" ", abc.Split('&', '|', '$')));
}

回答by Daniel van Dommele

what about:

关于什么:

return Regex.Replace(inputData, "[$\|\&]", " ");

回答by NucS

It is possible to do with Regex, but if you prefer for some reason to avoid it, use the following static extension:

可以使用Regex,但如果您出于某种原因希望避免它,请使用以下静态扩展名:

public static string ReplaceMultiple(this string target, string samples, char replaceWith) {
    if (string.IsNullOrEmpty(target) || string.IsNullOrEmpty(samples))
        return target;
    var tar = target.ToCharArray();
    for (var i = 0; i < tar.Length; i++) {
        for (var j = 0; j < samples.Length; j++) {
            if (tar[i] == samples[j]) {
                tar[i] = replaceWith;
                break;
            }
        }
    }
    return new string(tar);
}

Usage:

用法:

var target = "abc123abc123";
var replaced = target.ReplaceMultiple("ab2", 'x');
//replaced will result: "xxc1x3xxc1x3"