如何轻松检查字符串是否为空或只包含未确定数量的空格?
string.IsNullOrWhiteSpace
方法:if(string.IsNullOrWhiteSpace(myStringValue))
{
// ...
}
public static bool IsEmptyOrWhiteSpace(this string value) =>
value.All(char.IsWhiteSpace);
value?.All(char.IsWhiteSpace) ?? false
— 或者您可以使用不那么花哨的短路求值:value != null && value.All(char.IsWhiteSpace)
。 - PalecAll()
来确保一旦找到非空格字符就能有效地短路退出。 (这与Shimmy的方法大致相同,但仅回答了OP按照写作要求检查空格,而不是任何和所有空格-\t
,\n
,\r
,等等)/// <summary>
/// Ensure that the string is either the empty string `""` or contains
/// *ONLY SPACES* without any other character OR whitespace type.
/// </summary>
/// <param name="str">The string to check.</param>
/// <returns>`true` if string is empty or only made up of spaces. Otherwise `false`.</returns>
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
!enumerable.Any(x => !predicate(x))
= enumerable.All(x => predicate(x))
只是一种复杂的思维方式。 - Palecstring testMe = null; testMe.IndexOf("spam");
并得到 An unhandled exception of type 'System.NullReferenceException' occurred
,但这是 IndexOf
的“错”,而不是字符串为 null
的“错”。这证明了盲目模仿和大象口哨的错误。 “嘿,像在空字符串上调用 IndexOf
这样的字符串函数会出错。最好不要在空字符串上使用扩展方法。[在非空字符串上使用扩展方法永远不会出错。] 看到了吗?!” (◔_◔) - ruffinAll
更好,但他的答案也犯了和Merlyn一样的“错误”...空格字符集>空格字符集。;^) 我会编辑使用 All
。双重否定在我写它时看起来很奇怪,我只是添加了一个注释而没有弄清楚正确的方法...失败。只是想快速展示检查 null 不是一个巨大的负担,Merlyn似乎认为它是。/耸肩 感谢你的努力。 - ruffinif(string.IsNullOrEmpty(myStringValue.Trim()))
private bool IsNullOrEmptyOrAllSpaces(string str)
{
if(str == null || str.Length == 0)
{
return true;
}
for (int i = 0; i < str.Length; i++)
{
if (!Char.IsWhiteSpace(str[i])) return false;
}
return true;
}
尝试使用 LinQ 解决?
if(from c in yourString where c != ' ' select c).Count() != 0)
如果字符串不全为空格,则返回 true。
Enumerable.All<TSource>
采用短路求值,详见 .NET reference source。 - Palec
string.IsNullOrEmpty(YourString)
。 - sylverfyreIsNullOrEmpty
与IsNullOrWhiteSpace
。 - Merlyn Morgan-Grahamnull
、\t
、\r
和\n
,这些都不是空格。 /耸肩 虽然这基本上是Shimmy的副本,但添加了测试null的能力,而扩展方法无法做到。 - ruffin