String.IsNullOrEmpty()检查空间 [英] String.IsNullOrEmpty() Check for Space
问题描述
需要什么让 String.IsNullOrEmpty()
计空格的字符串作为空的?
What is needed to make String.IsNullOrEmpty()
count whitespace strings as empty?
例如。我想下面的返回真正
而不是通常的假
:
Eg. I want the following to return true
instead of the usual false
:
String.IsNullOrEmpty(" ");
难道还有比一个更好的方法:
Is there a better approach than:
String.IsNullOrEmpty(" ".Trim());
的(注意,原来的问题问什么回报将是正常因而绝情的意见,这已经换成了更合理的问题)。的
推荐答案
.NET 4.0将引入方法 String.IsNullOrWhiteSpace
。在那之前,你需要使用修剪
如果你要处理的空白字符串你处理空字符串的方法相同。
.NET 4.0 will introduce the method 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.
对于不使用.NET 4.0的代码,一个辅助方法来检查空
或空或空白字符串可以这样实现的:
For code not using .NET 4.0, a helper method to check for null
or empty or whitespace strings can be implemented like this:
public static bool IsNullOrWhiteSpace(string value)
{
if (String.IsNullOrEmpty(value))
{
return true;
}
return String.IsNullOrEmpty(value.Trim());
}
的
String.IsNullOrEmpty
将不执行任何修整,将只检查是否字符串是一个空引用或空字符串。
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()检查空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!