How to replace different/multiple chars with white space for each instance of character?
characters to be replaced are \ / : * ? < > |
How to replace different/multiple chars with white space for each instance of character?
characters to be replaced are \ / : * ? < > |
System.Text.RegularExpressions.Regex.Replace(input, @"[\\/:*?<>|]", " ")
Regex.Replace(@"my \ special / : string", @"[\\/:*?<>|]", " ");
I might have some of the escapes wrong... :/
Look at the String API methods in C#.
String.replace would work, if you called it seven times.
Or String.indexOfAny in a loop, using String.remove and String.insert.
Going the efficient lines of code way, Regexp.
You can achieve this with string.Split and string.Join:
string myString = string.Join(" ", input.Split(@"\/:*?<>|".ToCharArray()));
Out of curiousity tested this for performance, and it is considerably faster than the Regex approach.
Here's a compilable piece of code:
// input
string input = @"my \ ?? spe<<||>>cial / : string";
// regex
string test = Regex.Replace(input, @"[\\/:*?<>|]", " ");
// test now contains "my spe cial string"
Note: this post is a fix of the original JustLoren's code, it's not entirely mine.
You can do it using Regex
static void Main(string[] args)
{
string myStr = @"\ / : * ? < > |";
Regex myRegex = new Regex(@"\\|\/|\:|\*|\?|\<|\>|\|");
string replaced = myRegex.Replace(myStr, new MatchEvaluator(OnMatch));
Console.WriteLine(replaced);
}
private static string OnMatch(Match match)
{
return " ";
}