简体   繁体   English

String.IsNullOrEmpty()检查空格

[英]String.IsNullOrEmpty() Check for Space

What is needed to make String.IsNullOrEmpty() count whitespace strings as empty? 使String.IsNullOrEmpty()将空格字符串计为空是什么?

Eg. 例如。 I want the following to return true instead of the usual false : 我希望以下内容返回true而不是通常的false

String.IsNullOrEmpty(" ");

Is there a better approach than: 有没有比以下更好的方法:

 String.IsNullOrEmpty(" ".Trim());

(Note that the original question asked what the return would be normally hence the unsympathetic comments, this has been replaced with a more sensible question). (请注意,原始问题通常会回报什么是无情的评论,这已经被一个更明智的问题所取代)。

.NET 4.0 will introduce the method String.IsNullOrWhiteSpace . .NET 4.0将引入方法String.IsNullOrWhiteSpace Until then you'll need to use Trim if you want to deal with white space strings the same way you deal with empty strings. 在此之前,如果要处理空白字符串,则需要使用Trim就像处理空字符串一样。

For code not using .NET 4.0, a helper method to check for null or empty or whitespace strings can be implemented like this: 对于不使用.NET 4.0的代码,可以实现检查null或空或空格字符串的辅助方法,如下所示:

public static bool IsNullOrWhiteSpace(string value)
{
    if (String.IsNullOrEmpty(value))
    {
        return true;
    }

    return String.IsNullOrEmpty(value.Trim());
}

The String.IsNullOrEmpty will not perform any trimming and will just check if the string is a null reference or an empty string. String.IsNullOrEmpty不会执行任何修剪,只会检查字符串是空引用还是空字符串。

String.IsNullOrEmpty(" ")

...Returns False ...返回False

String foo = null;
String.IsNullOrEmpty( foo.Trim())

...Throws an exception as foo is Null. ...当foo为Null时抛出异常。

String.IsNullOrEmpty( foo ) || foo.Trim() == String.Empty

...Returns true ...返回true

Of course, you could implement it as an extension function: 当然,您可以将其实现为扩展功能:

static class StringExtensions
{
    public static bool IsNullOrWhiteSpace(this string value)
    {
        return (String.IsNullOrEmpty(value) || String.IsNullOrEmpty(value.Trim()));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM