• C# 对字符串判空方法


    方法一:

    1. static void Main(string[] args)
    2. {
    3. string str = "";
    4. if (str == "")
    5. {
    6. Console.WriteLine("a is empty"); ;
    7. }
    8. Console.ReadKey();
    9. }

    这样针对str = ""也是可以的,但是大多数场景是在方法的 入口处判空,这个字符串有可能是null,也有可能是"   ",甚至是"\n",上面这种判空方法显示不能覆盖这么多场景;

    方法二:这时候可以使用IsNullOrEmpty,针对字符串值为string.Empty、str2 = ""、null,都可以用

    1. static void Main(string[] args)
    2. {
    3. string str1 = string.Empty;
    4. if (string.IsNullOrEmpty(str1))
    5. {
    6. Console.WriteLine("str1 is empty"); ;
    7. }
    8. string str2 = "";
    9. if (string.IsNullOrEmpty(str2))
    10. {
    11. Console.WriteLine("str2 is empty"); ;
    12. }
    13. string str3 = null;
    14. if (string.IsNullOrEmpty(str3))
    15. {
    16. Console.WriteLine("str3 is empty"); ;
    17. }
    18. Console.ReadKey();
    19. }

    方法三 :但是IsNullOrEmpty在字符串为"     ","\n","\t",时候就无能为力了,为了覆盖这些场景,高手们一般判空使用方法IsNullOrWhiteSpace

    1. static void Main(string[] args)
    2. {
    3. string str1 = string.Empty;
    4. if (string.IsNullOrWhiteSpace(str1))
    5. {
    6. Console.WriteLine("str1 is empty"); ;
    7. }
    8. string str2 = "";
    9. if (string.IsNullOrWhiteSpace(str2))
    10. {
    11. Console.WriteLine("str2 is empty"); ;
    12. }
    13. string str3 = null;
    14. if (string.IsNullOrWhiteSpace(str3))
    15. {
    16. Console.WriteLine("str3 is empty"); ;
    17. }
    18. string str4 = " ";
    19. if (string.IsNullOrWhiteSpace(str4))
    20. {
    21. Console.WriteLine("str4 is empty"); ;
    22. }
    23. string str5 = "\n";
    24. if (string.IsNullOrWhiteSpace(str5))
    25. {
    26. Console.WriteLine("str5 is empty"); ;
    27. }
    28. string str6 = "\t";
    29. if (string.IsNullOrWhiteSpace(str6))
    30. {
    31. Console.WriteLine("str6 is empty"); ;
    32. }
    33. Console.ReadKey();
    34. }

  • 相关阅读:
    php项目从宝塔面板切换转到phpstudy小皮面板
    cobbler Centos7
    面试算法10:和为k的子数组
    一文读懂 Jetpack 组件开源库中 MVVM 框架架构
    Spring系列14:IoC容器的扩展点
    FFmpeg音频解码
    FISCO-BCOS添加新节点
    前端常见的设计模式
    二叉树详解(Java)
    详细讲解什么是单例模式
  • 原文地址:https://blog.csdn.net/yunxiaobaobei/article/details/126784643