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
You can use 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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With