简体   繁体   English

如何用空格替换多个不同的字符?

[英]How to replace multiple different chars with white space?

How 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.Split和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方法要快得多。

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

我可能有一些逃脱错误...:/

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

Look at the String API methods in C#. 查看C#中的String API方法。

String.replace would work, if you called it seven times. 如果您调用String.replace七次,它将起作用。
Or String.indexOfAny in a loop, using String.remove and String.insert. 或使用String.remove和String.insert循环执行String.indexOfAny。

Going the efficient lines of code way, Regexp. 要使用高效的代码方式,Regexp。

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. 注意:此文章是对JustLoren原始代码的修复,并不完全是我的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM