溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在.NET中刪除空白的字符串

發(fā)布時間:2021-01-04 15:49:17 來源:億速云 閱讀:218 作者:Leah 欄目:開發(fā)技術(shù)

怎么在.NET中刪除空白的字符串?針對這個問題,這篇文章詳細介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

檢查空白字符

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

char wp = ' '; 
char a = 'a'; 
Assert.True(char.IsWhiteSpace(wp)); 
Assert.False(char.IsWhiteSpace(a)); 
 
但是,當(dāng)我實現(xiàn)手動優(yōu)化刪除方法時,我意識到這并不像預(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()方法,而且實際上相當(dāng)快,但現(xiàn)在我們依次已經(jīng)有了4個方法調(diào)用!以下這段代碼是由一位評論者提供的,可用于快速實現(xiàn)定制版本和JIT默認內(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; 
  } 
}

刪除字符串的不同方法

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

分離合并法

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

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

正則表達式

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

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ù)非空白“字符串”的同時跳過空格。最后,它將創(chuàng)建一個適當(dāng)尺寸的字符數(shù)組,并用相同的方式返回一個新的字符串。

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)交換法

用代碼實現(xiàn)循環(huán),并使用StringBuilder類,通過依靠StringBuilder的內(nèi)在優(yōu)化來創(chuàng)建新的字符串。為了避免任何其他因素對本實施產(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();;
}

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

這種方法使用不安全的字符指針和指針運算來原地改變字符串。我不推薦這個方法,因為它打破了.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(不安全)

這種方法幾乎和前面那個相同,不過此處使用類似數(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(“”,“”)

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

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

關(guān)于怎么在.NET中刪除空白的字符串問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI