佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > 10個(gè).NET中刪除空白字符串的方法

10個(gè).NET中刪除空白字符串的方法

熱門標(biāo)簽:硅谷的囚徒呼叫中心 集中運(yùn)營管理辦法 阿里云 地方門戶網(wǎng)站 科大訊飛語音識別系統(tǒng) 百度競價(jià)排名 服務(wù)器配置 網(wǎng)站排名優(yōu)化

我們有無數(shù)方法可用于刪除字符串中的所有空白,但是哪個(gè)更快呢?

介紹

如果你問空白是什么,那說起來還真是有些亂。許多人認(rèn)為空白就是SPACE 字符(UnicodeU+0020,ASCII 32,HTML#32;),但它實(shí)際上還包括使得版式水平和垂直出現(xiàn)空格的所有字符。事實(shí)上,這是一整類定義為Unicode字符數(shù)據(jù)庫的字符。

本文所說的空白,不但指的是它的正確定義,同時(shí)也包括string.Replace(” “, “”)方法。

這里的基準(zhǔn)方法,將刪除所有頭尾和中間的空白。這就是文章標(biāo)題中“所有空白”的含義。

背景

這篇文章一開始是出于我的好奇心。事實(shí)上,我并不需要用最快的算法來刪除字符串中的空白。

檢查空白字符

檢查空白字符很簡單。所有你需要的代碼就是:

char wp = ' '; 
char a = 'a'; 
Assert.True(char.IsWhiteSpace(wp)); 
Assert.False(char.IsWhiteSpace(a)); 
 
但是,當(dāng)我實(shí)現(xiàn)手動(dòng)優(yōu)化刪除方法時(shí),我意識到這并不像預(yù)期得那么好。一些源代碼在微軟的參考源代碼庫的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()方法調(diào)用InternalGetUnicodeCategory()方法,而且實(shí)際上相當(dāng)快,但現(xiàn)在我們依次已經(jīng)有了4個(gè)方法調(diào)用!以下這段代碼是由一位評論者提供的,可用于快速實(shí)現(xiàn)定制版本和JIT默認(rèn)內(nèi)聯(lián): 
 

// 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; 
  } 
} 

刪除字符串的不同方法

我用各種不同的方法來實(shí)現(xiàn)刪除字符串中的所有空白。

分離合并法

這是我一直在用的一個(gè)非常簡單的方法。根據(jù)空格字符分離字符串,但不包括空項(xiàng),然后將產(chǎn)生的碎片重新合并到一起。這方法聽上去有點(diǎn)傻乎乎的,而事實(shí)上,乍一看,很像是一個(gè)非常浪費(fèi)的解決方式:

public static string TrimAllWithSplitAndJoin(string str) { 
  return string.Concat(str.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries)); 
} 
 
LINQ 
 
這是優(yōu)雅地聲明式地實(shí)現(xiàn)這個(gè)過程的方法: 
 
public static string TrimAllWithLinq(string str) { 
  return new string(str.Where(c => !isWhiteSpace(c)).ToArray()); 
} 

正則表達(dá)式

正則表達(dá)式是非常強(qiáng)大的力量,任何程序員都應(yīng)該意識到這一點(diǎn)。

static Regex whitespace = new Regex(@"\s+", RegexOptions.Compiled); 
 
public static string TrimAllWithRegex(string str) { 
  return whitespace.Replace(str, ""); 
} 

字符數(shù)組原地轉(zhuǎn)換法

該方法將輸入的字符串轉(zhuǎn)換成字符數(shù)組,然后原地掃描字符串去除空白字符(不創(chuàng)建中間緩沖區(qū)或字符串)。最后,經(jīng)過“刪減”的數(shù)組會產(chǎn)生新的字符串。

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); 
} 

字符數(shù)組復(fù)制法

這種方法類似于字符數(shù)組原地轉(zhuǎn)換法,但它使用Array.Copy復(fù)制連續(xù)非空白“字符串”的同時(shí)跳過空格。最后,它將創(chuàng)建一個(gè)適當(dāng)尺寸的字符數(shù)組,并用相同的方式返回一個(gè)新的字符串。

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);
}

循環(huán)交換法

用代碼實(shí)現(xiàn)循環(huán),并使用StringBuilder類,通過依靠StringBuilder的內(nèi)在優(yōu)化來創(chuàng)建新的字符串。為了避免任何其他因素對本實(shí)施產(chǎn)生干擾,不調(diào)用其他的方法,并且通過緩存到本地變量避免訪問類成員。最后通過設(shè)置StringBuilder.Length將緩沖區(qū)調(diào)整到合適大小。

// Code suggested by http://www.codeproject.com/Members/TheBasketcaseSoftware

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();;
}

循環(huán)字符法

這種方法幾乎和前面的循環(huán)交換法相同,不過它采用if語句來調(diào)用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();;
}

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

這種方法使用不安全的字符指針和指針運(yùn)算來原地改變字符串。我不推薦這個(gè)方法,因?yàn)樗蚱屏?NET框架在生產(chǎn)中的基本約定:字符串是不可變的。

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(不安全)

這種方法幾乎和前面那個(gè)相同,不過此處使用類似數(shù)組的指針訪問。我很好奇,不知道這兩種哪種存儲訪問會更快。

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(“”,“”)

這種實(shí)現(xiàn)方法很天真,由于它只替換空格字符,所以它不使用空白的正確定義,因此會遺漏很多其他的空格字符。雖然它應(yīng)該算是本文中最快的方法,但功能不及其他。

但如果你只需要去掉真正的空格字符,那就很難用純.NET寫出勝過string.Replace的代碼。大多數(shù)字符串方法將回退到手動(dòng)優(yōu)化本地C ++代碼。而String.Replace本身將用comstring.cpp調(diào)用C ++方法:

FCIMPL3(Object*, 
  COMString::ReplaceString, 
  StringObject* thisRefUNSAFE, 
  StringObject* oldValueUNSAFE, 
  StringObject* newValueUNSAFE)

下面是基準(zhǔn)測試套件方法:

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大方法,希望對大家的學(xué)習(xí)有所幫助。

您可能感興趣的文章:
  • 用于過濾空白字符的幾種常見的js正則表達(dá)式pattern
  • 用MySQL函數(shù)清除字符串首尾空白字符的方法
  • Perl刪除前導(dǎo)和拖尾空白(刪除左右空格、空白字符)
  • ASP.NET通過自定義函數(shù)實(shí)現(xiàn)對字符串的大小寫切換功能
  • PHP實(shí)現(xiàn)刪除字符串中任何字符的函數(shù)

標(biāo)簽:威海 開封 廣西 梧州 隨州 甘孜 西雙版納 烏蘭察布

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《10個(gè).NET中刪除空白字符串的方法》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    兴义市| 新宾| 长丰县| 博兴县| 彩票| 商南县| 五华县| 玛曲县| 綦江县| 玉环县| 麻江县| 东兰县| 丰台区| 任丘市| 运城市| 玉环县| 连云港市| 永城市| 旬邑县| 科技| 河池市| 云南省| 金堂县| 寿阳县| 南丹县| 南京市| 务川| 荔浦县| 常熟市| 旬阳县| 唐山市| 靖安县| 眉山市| 南郑县| 庄河市| 台山市| 尼木县| 高平市| 阜城县| 潼关县| 会泽县|