从大字符串中删除数字时的性能问题

时间:2013-01-19 14:57:58

标签: c# string

我有一个包含以下代码的函数:

Text = Text.Where(c => !Char.IsDigit(c)).Aggregate<char, string>(null, (current, c) => current + c);

但它很慢。无论如何我可以加快速度吗?

4 个答案:

答案 0 :(得分:8)

试试这个正则表达式:

Text = Regex.Replace(Text, @"\d+", "");

\d+\d效率更高,因为它会一次删除多个连续数字。

答案 1 :(得分:3)

是的,您可以使用Regex.Replace

Text = Regex.Replace(Text, "\\d", "");

正则表达式匹配单个数字。 Regex.Replace使用空字符串Text替换""字符串中每次出现的内容。

答案 2 :(得分:2)

所有这些连接都可能会杀了你。最简单/最好的可能是正则表达式:

Text = Regex.Replace(Text, "\\d", "");

或者您可以尝试只创建一个新的字符串实例:

Text = new string(Text.Where(c => !Char.IsDigit(c)).ToArray())

答案 3 :(得分:1)

尝试使用Regex.Replace;

  

在指定的输入字符串中,替换与常规字符串匹配的字符串   具有指定替换字符串的表达式模式。

Regex.Replace(Text, "\\d+", "");

这是DEMO