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

user2629770
  • 317
  • 2
  • 4
  • 8
  • check out http://stackoverflow.com/questions/12007358/alternative-to-string-replace-multiple-times, long story short, unless you want to make the code less readable then, no, not really. – Dutts Jul 30 '13 at 08:03

4 Answers4

41

You can use Regex.Replace:

string output = Regex.Replace(input, "[$|&]", " ");
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
7

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('&', '|', '$')));
}
Maxim Zhukov
  • 10,060
  • 5
  • 44
  • 88
1

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"
NucS
  • 619
  • 8
  • 21
0

what about:

return Regex.Replace(inputData, "[\$\|\&]", " ");
  • 1
    This code doesn't compile. You have to double-escape your Regex or either you have to prefix your string with `@`. – fero Jul 30 '13 at 08:11