介绍
怎么在。净中删除空白的字符串?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
<>强检查空白字符强>
检查空白字符很简单,所有你需要的代码就是:
char wp =, & # 39;,, & # 39; char a =, & # 39;一个# 39;,, 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),,//才能,Unicode 3.0,拷贝,U + 2028, is 从而only character which is under 从而category “LineSeparator"只//才能,以及U + 2029, is th eonly character which is under 从而category “ParagraphSeparator"只 switch 才能;(加州大学),{, ,,,case (UnicodeCategory.SpaceSeparator):, ,,,case (UnicodeCategory.LineSeparator):, ,,,case (UnicodeCategory.ParagraphSeparator):, ,,,,,return (真正的),, ,,}, , return 才能;(假),, }
GetUnicodeCategory()方法调用InternalGetUnicodeCategory()方法,而且实际上相当快,但现在我们依次已经有了4个方法调用!以下这段代码是由一位评论者提供的,可用于快速实现定制版本和JIT默认内联:,
,
//, whitespace detection 方法:,非常快,,a lot faster than Char.IsWhiteSpace [MethodImpl (MethodImplOptions.AggressiveInlining)],//, if 这# 39;s not inlined then it will be 慢! ! !, public static  bool isWhiteSpace (char ch), {,//才能,却;能够is surprisingly faster than 从而equivalent if statement switch 才能;(ch), {, ,,,case & # 39; \ u0009& # 39;:, case & # 39; \ u000A& # 39;:, case & # 39; \ u000B& # 39;:, case & # 39; \ u000C& # 39;:, case & # 39; \ u000D& # 39;:, ,,,case & # 39; \ u0020& # 39;:, case & # 39; \ u0085& # 39;:, case & # 39; \ u00A0& # 39;:, case & # 39; \ u1680& # 39;:, case & # 39; \ u2000& # 39;:, ,,,case & # 39; \ u2001& # 39;:, case & # 39; \ u2002& # 39;:, case & # 39; \ u2003& # 39;:, case & # 39; \ u2004& # 39;:, case & # 39; \ u2005& # 39;:, ,,,case & # 39; \ u2006& # 39;:, case & # 39; \ u2007& # 39;:, case & # 39; \ u2008& # 39;:, case & # 39; \ u2009& # 39;:, case & # 39; \ u200A& # 39;:, ,,,case & # 39; \ u2028& # 39;:, case & # 39; \ u2029& # 39;:, case & # 39; \ u202F& # 39;:, case & # 39; \ u205F& # 39;:, case & # 39; \ u3000& # 39;:, ,,,,,return ,真的,, ,,,默认值:, ,,,,,return 假的,, ,,}, }
<>强删除字符串的不同方法强>
我用各种不同的方法来实现删除字符串中的所有空白。
<强>分离合并法强>
这是我一直在用的一个非常简单的方法,根据空格字符分离字符串,但不包括空项,然后将产生的碎片重新合并到一起。这方法听上去有点傻乎乎的,而事实上,乍一看,很像是一个非常浪费的解决方式:
public static string TrimAllWithSplitAndJoin (string str), {, return 才能string.Concat (str.Split(默认(string []), StringSplitOptions.RemoveEmptyEntries)),, }, , LINQ , 这是优雅地声明式地实现这个过程的方法:, , public static  string TrimAllWithLinq (string str), {, return 才能;new 字符串(str.Where (c =祝辞,! isWhiteSpace (c)) .ToArray ()),, }
<>强正则表达式强>
正则表达式是非常强大的力量,任何程序员都应该意识到这一点。
static Regex whitespace =, new 正则表达式(@" \ s +“, RegexOptions.Compiled),, , public static  string TrimAllWithRegex (string str), {, return 才能;whitespace.Replace (str,,,,),, }怎么在。net中删除空白的字符串