17

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

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

4

4 回答 4

38

您可以使用Regex.Replace

string output = Regex.Replace(input, "[$|&]", " ");
于 2013-07-30T08:03:44.370 回答
6

您可以使用Split函数和String.Join下一步:

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

测试代码:

static void Main(string[] args)
{
     String abc = "asdfj$asdfj$sdfjn&sfnjdf|jnsdf|";
     Console.WriteLine(String.Join(" ", abc.Split('&', '|', '$')));
}
于 2013-07-30T08:04:14.093 回答
1

可以使用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);
}

用法:

var target = "abc123abc123";
var replaced = target.ReplaceMultiple("ab2", 'x');
//replaced will result: "xxc1x3xxc1x3"
于 2013-07-30T08:07:22.293 回答
0

关于什么:

return Regex.Replace(inputData, "[\$\|\&]", " ");
于 2013-07-30T08:06:24.527 回答