这个问题并不像其他海报所说的那么简单(正如我最初认为的那样)——因为这个问题并不像它需要的那样精确。
“空格”和“空白”是有区别的。如果您只指空格,那么您应该使用" {2,}"
. 如果您的意思是任何空格,那是另一回事。是否应该将所有空格都转换为空格?空间在开始和结束时应该发生什么?
对于下面的基准,我假设您只关心空格,并且您不想对单个空格做任何事情,即使在开始和结束时也是如此。
请注意,正确性几乎总是比性能更重要。就您指定的要求而言,Split/Join 解决方案删除任何前导/尾随空格(甚至只是单个空格)的事实是不正确的(当然,这可能是不完整的)。
基准测试使用MiniBench。
using System;
using System.Text.RegularExpressions;
using MiniBench;
internal class Program
{
public static void Main(string[] args)
{
int size = int.Parse(args[0]);
int gapBetweenExtraSpaces = int.Parse(args[1]);
char[] chars = new char[size];
for (int i=0; i < size/2; i += 2)
{
// Make sure there actually *is* something to do
chars[i*2] = (i % gapBetweenExtraSpaces == 1) ? ' ' : 'x';
chars[i*2 + 1] = ' ';
}
// Just to make sure we don't have a \0 at the end
// for odd sizes
chars[chars.Length-1] = 'y';
string bigString = new string(chars);
// Assume that one form works :)
string normalized = NormalizeWithSplitAndJoin(bigString);
var suite = new TestSuite<string, string>("Normalize")
.Plus(NormalizeWithSplitAndJoin)
.Plus(NormalizeWithRegex)
.RunTests(bigString, normalized);
suite.Display(ResultColumns.All, suite.FindBest());
}
private static readonly Regex MultipleSpaces =
new Regex(@" {2,}", RegexOptions.Compiled);
static string NormalizeWithRegex(string input)
{
return MultipleSpaces.Replace(input, " ");
}
// Guessing as the post doesn't specify what to use
private static readonly char[] Whitespace =
new char[] { ' ' };
static string NormalizeWithSplitAndJoin(string input)
{
string[] split = input.Split
(Whitespace, StringSplitOptions.RemoveEmptyEntries);
return string.Join(" ", split);
}
}
一些测试运行:
c:\Users\Jon\Test>test 1000 50
============ Normalize ============
NormalizeWithSplitAndJoin 1159091 0:30.258 22.93
NormalizeWithRegex 26378882 0:30.025 1.00
c:\Users\Jon\Test>test 1000 5
============ Normalize ============
NormalizeWithSplitAndJoin 947540 0:30.013 1.07
NormalizeWithRegex 1003862 0:29.610 1.00
c:\Users\Jon\Test>test 1000 1001
============ Normalize ============
NormalizeWithSplitAndJoin 1156299 0:29.898 21.99
NormalizeWithRegex 23243802 0:27.335 1.00
这里第一个数字是迭代次数,第二个是花费的时间,第三个是比例分数,1.0 是最好的。
这表明,至少在某些情况下(包括这种情况),正则表达式可以胜过 Split/Join 解决方案,有时甚至有很大的优势。
但是,如果您更改为“全空白”要求,那么拆分/加入似乎确实会赢。就像经常发生的那样,魔鬼在细节中......