简体   繁体   中英

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

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

你可以使用Regex.Replace

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

You can use Split function and String.Join next:

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

Test code:

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

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

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"

关于什么:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM