我正在调用一个REST API,并收到一个XML响应。它返回一个工作区名称列表,我正在编写一个快速的IsExistingWorkspace()方法。因为所有的工作空间都是由没有空格的连续字符组成的,我假设找出特定工作空间是否在列表中最简单的方法是删除所有空格(包括换行符)并这样做(XML是从web请求接收到的字符串):

XML.Contains("<name>" + workspaceName + "</name>");

我知道这是区分大小写的,我就靠这一点了。我只是需要一种方法来有效地删除字符串中的所有空白。我知道RegEx和LINQ可以做到,但我对其他想法持开放态度。我最关心的是速度。


当前回答

我发现不同的结果是正确的。我试图用一个空格替换所有空白,正则表达式非常慢。

return( Regex::Replace( text, L"\s+", L" " ) );

对我来说(在c++ cli中)最有效的方法是:

String^ ReduceWhitespace( String^ text )
{
  String^ newText;
  bool    inWhitespace = false;
  Int32   posStart = 0;
  Int32   pos      = 0;
  for( pos = 0; pos < text->Length; ++pos )
  {
    wchar_t cc = text[pos];
    if( Char::IsWhiteSpace( cc ) )
    {
      if( !inWhitespace )
      {
        if( pos > posStart ) newText += text->Substring( posStart, pos - posStart );
        inWhitespace = true;
        newText += L' ';
      }
      posStart = pos + 1;
    }
    else
    {
      if( inWhitespace )
      {
        inWhitespace = false;
        posStart = pos;
      }
    }
  }

  if( pos > posStart ) newText += text->Substring( posStart, pos - posStart );

  return( newText );
}

我首先尝试了上面的例程,分别替换每个字符,但不得不切换到为非空格部分执行子字符串。当应用到1,200,000字符的字符串时:

上面的程序可以在25秒内完成 上面的程序+单独的字符替换在95秒内 正则表达式在15分钟后中止。

其他回答

下面是RegEx解决方案的一个简单的线性替代方案。我不知道哪个更快;你必须对它进行基准测试。

static string RemoveWhitespace(string input)
{
    StringBuilder output = new StringBuilder(input.Length);

    for (int index = 0; index < input.Length; index++)
    {
        if (!Char.IsWhiteSpace(input, index))
        {
            output.Append(input[index]);
        }
    }
    return output.ToString();
}

我需要用空格替换字符串中的空白,但不能重复空格。例如,我需要转换如下内容:

"a b   c\r\n d\t\t\t e"

to

"a b c d e"

我使用了以下方法

private static string RemoveWhiteSpace(string value)
{
    if (value == null) { return null; }
    var sb = new StringBuilder();

    var lastCharWs = false;
    foreach (var c in value)
    {
        if (char.IsWhiteSpace(c))
        {
            if (lastCharWs) { continue; }
            sb.Append(' ');
            lastCharWs = true;
        }
        else
        {
            sb.Append(c);
            lastCharWs = false;
        }
    }
    return sb.ToString();
}

使用Linq,你可以这样写一个可读的方法:

    public static string RemoveAllWhitespaces(this string source)
    {
        return string.IsNullOrEmpty(source) ? source : new string(source.Where(x => !char.IsWhiteSpace(x)).ToArray());
    }

我想很多人来这里是为了消除空格。:

string s = "my string is nice";
s = s.replace(" ", "");

从字符串中删除所有空格的简单方法,"example"是初始字符串。

String.Concat(example.Where(c => !Char.IsWhiteSpace(c))