【发布时间】:2009-10-28 02:45:47
【问题描述】:
如何为每个字符实例用空格替换不同/多个字符?
要替换的字符是\ / : * ? < > |
【问题讨论】:
如何为每个字符实例用空格替换不同/多个字符?
要替换的字符是\ / : * ? < > |
【问题讨论】:
您可以使用 string.Split 和 string.Join 来实现:
string myString = string.Join(" ", input.Split(@"\/:*?<>|".ToCharArray()));
出于好奇对此进行了性能测试,它比正则表达式方法快得多。
【讨论】:
string.Join 而不是 Split(..).Join()):)
Regex.Replace(@"my \ special / : string", @"[\\/:*?<>|]", " ");
我可能有一些转义错误...:/
【讨论】:
Regex.Replace(@"my \ ?? special / : string", @"[\\/:\*?<>|]", " ");(请注意,\? 等是允许的,但在字符类中不是必需的)
System.Text.RegularExpressions.Regex.Replace(input, @"[\\/:*?<>|]", " ")
【讨论】:
-、[ 和 `\` 除外。
如果你调用它七次,String.replace 会起作用。
或者 String.indexOfAny 在一个循环中,使用 String.remove 和 String.insert。
采用高效的代码行方式,正则表达式。
【讨论】:
你可以使用正则表达式来做到这一点
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 " ";
}
【讨论】:
这是一段可编译的代码:
// input
string input = @"my \ ?? spe<<||>>cial / : string";
// regex
string test = Regex.Replace(input, @"[\\/:*?<>|]", " ");
// test now contains "my spe cial string"
注意:这篇文章是对原始 JustLoren 代码的修复,并不完全是我的。
【讨论】: