繁体   English   中英

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

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

对于每个字符实例,如何用空格替换不同/多个字符?

要替换的字符是\\ / : * ? < > | \\ / : * ? < > |

您可以使用string.Split和string.Join实现此目的:

string myString = string.Join(" ", input.Split(@"\/:*?<>|".ToCharArray())); 

出于好奇,对它的性能进行了测试,它比Regex方法要快得多。

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

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

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

查看C#中的String API方法。

如果您调用String.replace七次,它将起作用。
或使用String.remove和String.insert循环执行String.indexOfAny。

要使用高效的代码方式,Regexp。

这是一段可编译的代码:

// input
string input = @"my \ ?? spe<<||>>cial / : string";

// regex
string test = Regex.Replace(input, @"[\\/:*?<>|]", " ");

// test now contains "my      spe      cial     string"

注意:此文章是对JustLoren原始代码的修复,并不完全是我的。

您可以使用正则表达式

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