c#去除多余空格的最快方法 [英] c# Fastest way to remove extra white spaces
问题描述
将多余的空格替换为一个空格的最快方法是什么?
例如
What is the fastest way to replace extra white spaces to one white space?
e.g.
来自
foo bar
到
foo bar
推荐答案
最快的方法?遍历字符串并在 StringBuilder
中逐个字符地构建第二个副本,只为每组空格复制一个空格.
The fastest way? Iterate over the string and build a second copy in a StringBuilder
character by character, only copying one space for each group of spaces.
更容易键入 Replace
变体将创建大量额外字符串(或浪费时间构建正则表达式 DFA).
The easier to type Replace
variants will create a bucket load of extra strings (or waste time building the regex DFA).
使用比较结果进行
使用 http://ideone.com/NV6EzU,n=50(必须在 ideone 上减少它因为他们不得不终止我的进程花了很长时间),我明白了:
Using http://ideone.com/NV6EzU, with n=50 (had to reduce it on ideone because it took so long they had to kill my process), I get:
正则表达式:7771 毫秒.
Regex: 7771ms.
字符串生成器:894 毫秒.
Stringbuilder: 894ms.
正如预期的那样,Regex
对于这么简单的事情来说效率非常低.
Which is indeed as expected, Regex
is horribly inefficient for something this simple.
这篇关于c#去除多余空格的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!