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性能更高一些,推荐使用。可以测试一下。

  • 相关阅读:
    input框限制只能输入正整数、字母、小数、
    css水平垂直居中
    Android开发之旅-获取地理位置的经度和纬度
    Android DDMS应用
    Android开发BUG及解决方法2
    Android开发BUG及解决方法1
    Android开发BUG及解决方法
    Android系统架构
    1.sql简介
    C语言笔试常考知识点
  • 原文地址:https://www.cnblogs.com/djd66/p/15247241.html
Copyright © 2011-2022 走看看