检查字符串是否为空或C#中的所有空格

如何轻松检查字符串是否为空白或是否包含未确定的空格量?

如果您有.NET 4,请使用string.IsNullOrWhiteSpace方法 :

 if(string.IsNullOrWhiteSpace(myStringValue)) { // ... } 

如果你没有.NET 4,并且你可以修改你的字符串,你可以先修剪它,然后检查它是否为空。

否则,你可以考虑自己实现它:

.Net 3.5使用代码约定实现String.IsNullOrWhitespace

如果您已经知道该字符串不为null,并且您只是想确保它不是空字符串,请使用以下命令:

 public static bool IsEmptyOrWhiteSpace(this string value) => value.All(char.IsWhiteSpace); 

尝试用LinQ解决?

 if(from c in yourString where c != ' ' select c).Count() != 0) 

如果字符串不是所有空格,则返回true。

如果你确实需要知道“字符串是空白还是满是一定数量的空格”,请使用LINQ作为@Sonia_yt建议,但使用All()以确保在找到后立即有效地短路非空间。

(这是给予或采取与Shimmy相同的,但回答OP的问题,因为写入检查空格,而不是任何和所有空格 – \t\n\r \n 等 )

 ///  /// Ensure that the string is either the empty string `""` or contains /// *ONLY SPACES* without any other character OR whitespace type. ///  /// The string to check. /// `true` if string is empty or only made up of spaces. Otherwise `false`. public static bool IsEmptyOrAllSpaces(this string str) { return null != str && str.All(c => c.Equals(' ')); } 

并在控制台应用程序中测试它…

 Console.WriteLine(" ".IsEmptyOrAllSpaces()); // true Console.WriteLine("".IsEmptyOrAllSpaces()); // true Console.WriteLine(" BOO ".IsEmptyOrAllSpaces()); // false string testMe = null; Console.WriteLine(testMe.IsEmptyOrAllSpaces()); // false