开发者

How to replace multiple different chars with white space?

How开发者_如何学Python to replace different/multiple chars with white space for each instance of character?

characters to be replaced are \ / : * ? < > |


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.


Regex.Replace(@"my \ special / : string", @"[\\/:*?<>|]", " ");

I might have some of the escapes wrong... :/


System.Text.RegularExpressions.Regex.Replace(input, @"[\\/:*?<>|]", " ")


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 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 " ";
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜