【发布时间】:2020-11-13 09:08:41
【问题描述】:
如何轻松检查字符串是否为空白或是否充满不确定数量的空格?
【问题讨论】:
标签: c# string whitespace
如何轻松检查字符串是否为空白或是否充满不确定数量的空格?
【问题讨论】:
标签: c# string whitespace
如果你有 .NET 4,use the string.IsNullOrWhiteSpace method:
if(string.IsNullOrWhiteSpace(myStringValue))
{
// ...
}
如果你没有.NET 4,并且你可以忍受修剪你的字符串,你可以先修剪它,然后检查它是否为空。
否则,您可以考虑自己实现它:
.Net 3.5 Implementation of String.IsNullOrWhitespace with Code Contracts
【讨论】:
string.IsNullOrEmpty(YourString)
IsNullOrEmpty 与 IsNullOrWhiteSpace
null、\t、\r 和\n 中出现,它们不是空格. /shrug 虽然这基本上欺骗了 Shimmy,但增加了测试空值的能力,这是扩展方法无法做到的。
如果您已经知道该字符串不为空,并且您只想确保它不是空白字符串,请使用以下内容:
public static bool IsEmptyOrWhiteSpace(this string value) =>
value.All(char.IsWhiteSpace);
【讨论】:
value?.All(char.IsWhiteSpace) ?? false — 或者您可以使用不太花哨的短路评估:value != null && value.All(char.IsWhiteSpace)
如果您确实需要知道“字符串是空白还是充满了不确定数量的空格”,请按照@Sonia_yt 的建议使用 LINQ,但使用All() 以确保您在完成后立即有效地短路'已经找到了一个非空间。
(这与 Shimmy 的相同或相同,但回答了写给 OP 的问题,仅检查空格,而不是任何和所有空格 -- \t、\n、@ 987654326@,etc.)
/// <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)) 只是令人费解的想法。
string testMe = null; testMe.IndexOf("spam"); 并得到An unhandled exception of type 'System.NullReferenceException' occurred,但这是IndexOf 的“错误”,而不是字符串是null。货物培养得一分/elephant whistles。 “嘿,在空字符串上调用 IndexOf 之类的字符串函数会中断。最好不要对空字符串使用扩展方法。[对非空字符串使用扩展方法永远不会中断。] 看到了吗?!”(◔ _◔)
All 更好,但他的回答也犯了与 Merlyn 相同的“错误”……空白字符集 > 空格字符集。 ;^) 我将编辑使用All。当我写它的时候,双重否定看起来很奇怪,我只是添加了一条评论,而不是找出正确的事情……失败。只是想快速表明检查 null 并不是一个巨大的负担,Merlyn 似乎暗示了这一点。 /耸耸肩谢谢你的收获。
试试用LinQ解决?
if(from c in yourString where c != ' ' select c).Count() != 0)
如果字符串不是全是空格,这将返回 true。
【讨论】:
Enumerable.All<TSource> 采用短路评估,请参阅 .NET reference source。
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;
}
【讨论】: