10個(gè).NET中刪除空白字符串的方法
我們有無(wú)數(shù)方法可用于刪除字符串中的所有空白,但是哪個(gè)更快呢?
介紹
如果你問(wèn)空白是什么,那說(shuō)起來(lái)還真是有些亂。許多人認(rèn)為空白就是SPACE 字符(UnicodeU+0020,ASCII 32,HTML ),但它實(shí)際上還包括使得版式水平和垂直出現(xiàn)空格的所有字符。事實(shí)上,這是一整類(lèi)定義為Unicode字符數(shù)據(jù)庫(kù)的字符。
本文所說(shuō)的空白,不但指的是它的正確定義,同時(shí)也包括string.Replace(” “, “”)方法。
這里的基準(zhǔn)方法,將刪除所有頭尾和中間的空白。這就是文章標(biāo)題中“所有空白”的含義。
背景
這篇文章一開(kāi)始是出于我的好奇心。事實(shí)上,我并不需要用最快的算法來(lái)刪除字符串中的空白。
檢查空白字符
檢查空白字符很簡(jiǎn)單。所有你需要的代碼就是:
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í),我意識(shí)到這并不像預(yù)期得那么好。一些源代碼在微軟的參考源代碼庫(kù)的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)用!以下這段代碼是由一位評(píng)論者提供的,可用于快速實(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; } }
刪除字符串的不同方法
我用各種不同的方法來(lái)實(shí)現(xiàn)刪除字符串中的所有空白。
分離合并法
這是我一直在用的一個(gè)非常簡(jiǎn)單的方法。根據(jù)空格字符分離字符串,但不包括空項(xiàng),然后將產(chǎn)生的碎片重新合并到一起。這方法聽(tīng)上去有點(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è)過(guò)程的方法: public static string TrimAllWithLinq(string str) { return new string(str.Where(c => !isWhiteSpace(c)).ToArray()); }
正則表達(dá)式
正則表達(dá)式是非常強(qiáng)大的力量,任何程序員都應(yīng)該意識(shí)到這一點(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)過(guò)“刪減”的數(shù)組會(huì)產(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ù)制法
這種方法類(lèi)似于字符數(shù)組原地轉(zhuǎn)換法,但它使用Array.Copy復(fù)制連續(xù)非空白“字符串”的同時(shí)跳過(guò)空格。最后,它將創(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類(lèi),通過(guò)依靠StringBuilder的內(nèi)在優(yōu)化來(lái)創(chuàng)建新的字符串。為了避免任何其他因素對(duì)本實(shí)施產(chǎn)生干擾,不調(diào)用其他的方法,并且通過(guò)緩存到本地變量避免訪問(wèn)類(lèi)成員。最后通過(guò)設(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)交換法相同,不過(guò)它采用if語(yǔ)句來(lái)調(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)算來(lái)原地改變字符串。我不推薦這個(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è)相同,不過(guò)此處使用類(lèi)似數(shù)組的指針訪問(wèn)。我很好奇,不知道這兩種哪種存儲(chǔ)訪問(wèn)會(huì)更快。
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)方法很天真,由于它只替換空格字符,所以它不使用空白的正確定義,因此會(huì)遺漏很多其他的空格字符。雖然它應(yīng)該算是本文中最快的方法,但功能不及其他。
但如果你只需要去掉真正的空格字符,那就很難用純.NET寫(xiě)出勝過(guò)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)測(cè)試套件方法:
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大方法,希望對(duì)大家的學(xué)習(xí)有所幫助。
相關(guān)文章
OpenCV 3.1.0+VS2015開(kāi)發(fā)環(huán)境配置教程
這篇文章主要為大家詳細(xì)介紹了OpenCV 3.1.0+VS2015開(kāi)發(fā)環(huán)境配置教程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11.NET中求復(fù)雜類(lèi)型集合的差集、交集、并集
這篇文章主要介紹了.NET的求復(fù)雜類(lèi)型集合的差集、交集、并集,下面我將帶著大家去了解如何通過(guò)微軟自帶方法方式去取**復(fù)雜類(lèi)型集合**的差集、交集、并集,需要的朋友可以參考下2022-07-07ASP.NET MVC過(guò)濾器執(zhí)行順序介紹
這篇文章介紹了ASP.NET MVC過(guò)濾器的執(zhí)行順序,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-03-03ASP.net在頁(yè)面所有內(nèi)容生成后、輸出內(nèi)容前對(duì)頁(yè)面內(nèi)容進(jìn)行操作
ASP.net在頁(yè)面所有內(nèi)容生成后、輸出內(nèi)容前對(duì)頁(yè)面內(nèi)容進(jìn)行操作...2007-04-04.Net RabbitMQ實(shí)現(xiàn)HTTP API接口調(diào)用
RabbitMQ Management插件還提供了基于RESTful風(fēng)格的HTTP API接口來(lái)方便調(diào)用。本文就主要介紹了.Net RabbitMQ實(shí)現(xiàn)HTTP API接口調(diào)用,感興趣的可以了解一下2021-06-06