代码之家  ›  专栏  ›  技术社区  ›  Matthew Jones

有什么理由在上面使用这个Regex方法吗String.IsNullOrEmpty()?

  •  1
  • Matthew Jones  · 技术社区  · 15 年前

    public static bool isStringOnlyWhitespace(string toEval)
    {
        string stringNoWhitespace = Regex.Replace(toEval, @"\s", "");
        if (stringNoWhitespace.Length > 0) return false;
        else return true;
    }
    

    4 回复  |  直到 15 年前
        1
  •  10
  •   Matt Greer    15 年前

    当然,如果您正在寻找更难阅读的较慢代码:)

    你真的想用吗 string.IsNullOrWhitespace myString.Trim().Length == 0 那样的话。

        2
  •  2
  •   Justin Niessner    15 年前

    您提供的方法不处理空值 String.IsNullOrEmpty 做。

    这将向我表明,向方法传递null值是一种错误条件,它的行为与 String.IsNullOrEmpty .

    isStringOnlyWhitespace(" ") 鉴于 String.IsNullOrEmpty(" ")

        3
  •  1
  •   recursive    15 年前

    对。只包含空格的字符串不被认为是空的。 isStringOnlyWhitespace(" ") 返回true,但是 string.IsNullOrEmpty(" ")

        4
  •  1
  •   Zebi    15 年前

    否;)

    a) 我想既然.NET4你可以用string.isNullor空白

    b) 试试这样的

    public static bool IsStringOnlyWhitespace(this string str)
    {
        // if you want to check for null:
        return str == null || string.IsNullOrEmpty(str.Trim());
        // else
        return string.IsNullOrEmpty(string.Trim());
    }