Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

replace

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

like image 818
user2629770 Avatar asked Jul 30 '13 08:07

user2629770


3 Answers

You can use Regex.Replace:

string output = Regex.Replace(input, "[$|&]", " ");
like image 77
MarcinJuraszek Avatar answered Oct 19 '22 02:10

MarcinJuraszek


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('&', '|', '$')));
}
like image 44
Maxim Zhukov Avatar answered Oct 19 '22 02:10

Maxim Zhukov


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"
like image 1
NucS Avatar answered Oct 19 '22 03:10

NucS