zoukankan      html  css  js  c++  java
  • String.IsNullOrWhiteSpace和String.IsNullOrEmpty的区别

    以前刚入行的时候判断字符串的时候用

    string a="a";
    a=="";
    a==null;

    后来发现了String.IsNullOrEmpty感觉方便了好多,但是后来发现如果字符串的空白String a="  ";IsNullOrEmpty就没法判断了,于是我今天发现了String.IsNullOrWhiteSpace,此方法只在framework4.0以上才能使用,官方的解释是:指示指定的字符串是 null、空还是仅由空白字符组成。

    http://msdn.microsoft.com/zh-cn/library/system.string.isnullorwhitespace(v=vs.100).aspx

    string a = null;
                string b = string.Empty;
                string c = "";
                string d = "  ";
                Console.WriteLine("a:{0};
     b:{1};
     c:{2};
     d:{3};
    ", a, b, c, d);
                if (string.IsNullOrEmpty(a))
                    Console.WriteLine("a");
                if (string.IsNullOrEmpty(b))
                    Console.WriteLine("b");
                if (string.IsNullOrEmpty(c))
                    Console.WriteLine("c");
                if (string.IsNullOrEmpty(d))
                    Console.WriteLine("d");
    
                if (string.IsNullOrWhiteSpace(a))
                    Console.WriteLine("a1");
                if (string.IsNullOrWhiteSpace(b))
                    Console.WriteLine("b1");
                if (string.IsNullOrWhiteSpace(c))
                    Console.WriteLine("c1");
                if (string.IsNullOrWhiteSpace(d))
                    Console.WriteLine("d1");
                Console.Read();

    执行结果:

    由此可见当用IsNullOrEmpty时,d是没有输出来的,但是string.IsNullOrWhiteSpace却可以,如果执意要用前者又要判断空白的话,不妨与Trim组合使用。

    [转]https://www.cnblogs.com/tony312ws/p/3727179.html

    另一篇文章分析了源码:https://www.cnblogs.com/songwenjie/p/8657579.html

    表示:IsNullOrWhiteSpace是IsNullOrEmpty的加强

    MSDN说,IsNullOrWhiteSpace性能更高一些,推荐使用。可以测试一下。

  • 相关阅读:
    HDR算法(一)
    机器视觉话题入门资料---能看懂大致原理再去纠细节
    WRT callback
    dependency of static library
    dll 和 lib--初级
    memory corruption
    Python~函数的参数
    Python~函数
    Python~if,while,for~顺序,判断,循环
    Python~list,tuple^_^dict,set
  • 原文地址:https://www.cnblogs.com/djd66/p/15247241.html
Copyright © 2011-2022 走看看