当前位置: 移动技术网 > IT编程>开发语言>.net > 10个.NET中删除空白字符串的方法

10个.NET中删除空白字符串的方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

殁漂遥,小眯自述,启示的近义词

我们有无数方法可用于删除字符串中的所有空白,但是哪个更快呢?

介绍

如果你问空白是什么,那说起来还真是有些乱。许多人认为空白就是space 字符(unicodeu+0020,ascii 32,html ),但它实际上还包括使得版式水平和垂直出现空格的所有字符。事实上,这是一整类定义为unicode字符数据库的字符。

本文所说的空白,不但指的是它的正确定义,同时也包括string.replace(” “, “”)方法。

这里的基准方法,将删除所有头尾和中间的空白。这就是文章标题中“所有空白”的含义。

背景

这篇文章一开始是出于我的好奇心。事实上,我并不需要用最快的算法来删除字符串中的空白。

检查空白字符

检查空白字符很简单。所有你需要的代码就是:

char wp = ' '; 
char a = 'a'; 
assert.true(char.iswhitespace(wp)); 
assert.false(char.iswhitespace(a)); 
 
但是,当我实现手动优化删除方法时,我意识到这并不像预期得那么好。一些源代码在微软的参考源代码库的char.cs挖掘找到: 
 
public static bool iswhitespace(char c) { 
  if (islatin1(c)) { 
    return (iswhitespacelatin1(c)); 
  } 
  return charunicodeinfo.iswhitespace(c); 
} 
 
然后charunicodeinfo.iswhitespace成了: 
 
internal static bool iswhitespace(char c) 
{ 
  unicodecategory uc = getunicodecategory(c); 
  // in unicode 3.0, u+2028 is the only character which is under the category "lineseparator". 
  // and u+2029 is th eonly character which is under the category "paragraphseparator". 
  switch (uc) { 
    case (unicodecategory.spaceseparator): 
    case (unicodecategory.lineseparator): 
    case (unicodecategory.paragraphseparator): 
      return (true); 
  } 
 
  return (false); 
} 
 

getunicodecategory()方法调用internalgetunicodecategory()方法,而且实际上相当快,但现在我们依次已经有了4个方法调用!以下这段代码是由一位评论者提供的,可用于快速实现定制版本和jit默认内联: 
 

// whitespace detection method: very fast, a lot faster than char.iswhitespace 
[methodimpl(methodimploptions.aggressiveinlining)] // if it's not inlined then it will be slow!!! 
public static bool iswhitespace(char ch) { 
  // this is surprisingly faster than the equivalent if statement 
  switch (ch) { 
    case '\u0009': case '\u000a': case '\u000b': case '\u000c': case '\u000d': 
    case '\u0020': case '\u0085': case '\u00a0': case '\u1680': case '\u2000': 
    case '\u2001': case '\u2002': case '\u2003': case '\u2004': case '\u2005': 
    case '\u2006': case '\u2007': case '\u2008': case '\u2009': case '\u200a': 
    case '\u2028': case '\u2029': case '\u202f': case '\u205f': case '\u3000': 
      return true; 
    default: 
      return false; 
  } 
} 

删除字符串的不同方法

我用各种不同的方法来实现删除字符串中的所有空白。

分离合并法

这是我一直在用的一个非常简单的方法。根据空格字符分离字符串,但不包括空项,然后将产生的碎片重新合并到一起。这方法听上去有点傻乎乎的,而事实上,乍一看,很像是一个非常浪费的解决方式:

public static string trimallwithsplitandjoin(string str) { 
  return string.concat(str.split(default(string[]), stringsplitoptions.removeemptyentries)); 
} 
 
linq 
 
这是优雅地声明式地实现这个过程的方法: 
 
public static string trimallwithlinq(string str) { 
  return new string(str.where(c => !iswhitespace(c)).toarray()); 
} 

正则表达式

正则表达式是非常强大的力量,任何程序员都应该意识到这一点。

static regex whitespace = new regex(@"\s+", regexoptions.compiled); 
 
public static string trimallwithregex(string str) { 
  return whitespace.replace(str, ""); 
} 

字符数组原地转换法

该方法将输入的字符串转换成字符数组,然后原地扫描字符串去除空白字符(不创建中间缓冲区或字符串)。最后,经过“删减”的数组会产生新的字符串。

public static string trimallwithinplacechararray(string str) { 
  var len = str.length; 
  var src = str.tochararray(); 
  int dstidx = 0; 
  for (int i = 0; i < len; i++) { 
    var ch = src[i]; 
    if (!iswhitespace(ch)) 
      src[dstidx++] = ch; 
  } 
  return new string(src, 0, dstidx); 
} 

字符数组复制法

这种方法类似于字符数组原地转换法,但它使用array.copy复制连续非空白“字符串”的同时跳过空格。最后,它将创建一个适当尺寸的字符数组,并用相同的方式返回一个新的字符串。

public static string trimallwithchararraycopy(string str) {
  var len = str.length;
  var src = str.tochararray();
  int srcidx = 0, dstidx = 0, count = 0;
  for (int i = 0; i < len; i++) {
    if (iswhitespace(src[i])) {
      count = i - srcidx;
      array.copy(src, srcidx, src, dstidx, count);
      srcidx += count + 1;
      dstidx += count;
      len--;
    }
  }
  if (dstidx < len)
    array.copy(src, srcidx, src, dstidx, len - dstidx);
  return new string(src, 0, len);
}

循环交换法

用代码实现循环,并使用stringbuilder类,通过依靠stringbuilder的内在优化来创建新的字符串。为了避免任何其他因素对本实施产生干扰,不调用其他的方法,并且通过缓存到本地变量避免访问类成员。最后通过设置stringbuilder.length将缓冲区调整到合适大小。

// code suggested by

public static string trimallwithlexerloop(string s) {
  int length = s.length;
  var buffer = new stringbuilder(s);
  var dstidx = 0;
  for (int index = 0; index < s.length; index++) {
    char ch = s[index];
    switch (ch) {
      case '\u0020': case '\u00a0': case '\u1680': case '\u2000': case '\u2001':
      case '\u2002': case '\u2003': case '\u2004': case '\u2005': case '\u2006':
      case '\u2007': case '\u2008': case '\u2009': case '\u200a': case '\u202f':
      case '\u205f': case '\u3000': case '\u2028': case '\u2029': case '\u0009':
      case '\u000a': case '\u000b': case '\u000c': case '\u000d': case '\u0085':
        length--;
        continue;
      default:
        break;
    }
    buffer[dstidx++] = ch;
  }
  buffer.length = length;
  return buffer.tostring();;
}

循环字符法

这种方法几乎和前面的循环交换法相同,不过它采用if语句来调用iswhitespace(),而不是乱七八糟的switch伎俩 :)。

public static string trimallwithlexerloopchariswhitespce(string s) {
  int length = s.length;
  var buffer = new stringbuilder(s);
  var dstidx = 0;
  for (int index = 0; index < s.length; index++) {
    char currentchar = s[index];
    if (iswhitespace(currentchar))
      length--;
    else
      buffer[dstidx++] = currentchar;
  }
  buffer.length = length;
  return buffer.tostring();;
}

原地改变字符串法(不安全)

这种方法使用不安全的字符指针和指针运算来原地改变字符串。我不推荐这个方法,因为它打破了.net框架在生产中的基本约定:字符串是不可变的。

public static unsafe string trimallwithstringinplace(string str) {
  fixed (char* pfixed = str) {
    char* dst = pfixed;
    for (char* p = pfixed; *p != 0; p++)
      if (!iswhitespace(*p))
        *dst++ = *p;

/*// reset the string size
      * only it didn't work! a garbage collection access violation occurred after using it
      * so i had to resort to return a new string instead, with only the pertinent bytes
      * it would be a lot faster if it did work though...
    int32 len = (int32)(dst - pfixed);
    int32* pi = (int32*)pfixed;
    pi[-1] = len;
    pfixed[len] = '\0';*/
    return new string(pfixed, 0, (int)(dst - pfixed));
  }
}

原地改变字符串法v2(不安全)

这种方法几乎和前面那个相同,不过此处使用类似数组的指针访问。我很好奇,不知道这两种哪种存储访问会更快。

public static unsafe string trimallwithstringinplacev2(string str) {
  var len = str.length;
  fixed (char* pstr = str) {
    int dstidx = 0;
    for (int i = 0; i < len; i++)
      if (!iswhitespace(pstr[i]))
        pstr[dstidx++] = pstr[i];
    // since the unsafe string length reset didn't work we need to resort to this slower compromise
    return new string(pstr, 0, dstidx);
  }
}

string.replace(“”,“”)

这种实现方法很天真,由于它只替换空格字符,所以它不使用空白的正确定义,因此会遗漏很多其他的空格字符。虽然它应该算是本文中最快的方法,但功能不及其他。

但如果你只需要去掉真正的空格字符,那就很难用纯.net写出胜过string.replace的代码。大多数字符串方法将回退到手动优化本地c ++代码。而string.replace本身将用comstring.cpp调用c ++方法:

fcimpl3(object*, 
  comstring::replacestring, 
  stringobject* thisrefunsafe, 
  stringobject* oldvalueunsafe, 
  stringobject* newvalueunsafe)

下面是基准测试套件方法:

public static string trimallwithstringreplace(string str) {
  // this method is not functionaly equivalent to the others as it will only trim "spaces"
  // whitespace comprises lots of other characters
  return str.replace(" ", "");
}

以上就是.net中删除空白字符串的10大方法,希望对大家的学习有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网