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

     1             string a = null;
     2             string b = string.Empty;
     3             string c = "";
     4             string d = "  ";
     5             Console.WriteLine("a:{0};
     b:{1};
     c:{2};
     d:{3};
    ", a, b, c, d);
     6             if (string.IsNullOrEmpty(a))
     7                 Console.WriteLine("a");
     8             if (string.IsNullOrEmpty(b))
     9                 Console.WriteLine("b");
    10             if (string.IsNullOrEmpty(c))
    11                 Console.WriteLine("c");
    12             if (string.IsNullOrEmpty(d))
    13                 Console.WriteLine("d");
    14 
    15             if (string.IsNullOrWhiteSpace(a))
    16                 Console.WriteLine("a1");
    17             if (string.IsNullOrWhiteSpace(b))
    18                 Console.WriteLine("b1");
    19             if (string.IsNullOrWhiteSpace(c))
    20                 Console.WriteLine("c1");
    21             if (string.IsNullOrWhiteSpace(d))
    22                 Console.WriteLine("d1");
    23             Console.Read();    

    执行结果:

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

  • 相关阅读:
    HDU 5919 分块做法
    HDU 3333 分块求区间不同数和
    CF 333E 计算几何+bitset优化
    hdu 1043 八数码--打表
    hdu 1043 八数码问题-A*搜索
    hdu 5919 主席树
    hiho1388 FFT/NTT
    HDU 5869区间CGD不同种类数---树状数组+map统计区间不同种类数(离线)
    HDU 5875 二分+st表
    HDU 5898 基础数位DP
  • 原文地址:https://www.cnblogs.com/tony312ws/p/3727179.html
Copyright © 2011-2022 走看看