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

时间:2011-09-16 00:29:02

标签: c# string whitespace

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

5 个答案:

答案 0 :(得分:57)

如果你有.NET 4,use the string.IsNullOrWhiteSpace method

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

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

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

.Net 3.5 Implementation of String.IsNullOrWhitespace with Code Contracts

答案 1 :(得分:30)

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

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

答案 2 :(得分:0)

尝试使用LinQ解决?

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

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

答案 3 :(得分:0)

如果您确实需要知道"字符串是空白还是满是未确定的空格数",请使用LINQ作为@Sonia_yt建议,但使用All()以确保您有效地缩短 - 一旦你找到了非空间,就把电路输出。

(这与Shimmy相同,但是回答了OP的问题,只写 检查空格,而不是任何和所有空格 - { {1}},\t\netc.

\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(' '));
}

答案 4 :(得分:-1)

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;
}