当前位置: 首页 > news >正文

C# 字符串(string)三个不同的处理方法:IsNullOrEmpty、IsInterned 、IsNullOrWhiteSpace

在C#中,string.IsNullOrEmptystring.IsInternedstring.IsNullOrWhiteSpace 是三个不同的字符串处理方法,它们各自有不同的用途:

1.string.IsNullOrEmpty

这个方法用来检查字符串是否为null或者空字符串("")。如果字符串为null或者长度为0,那么这个方法返回true

string.IsNullOrEmpty(null); // 返回 true
string.IsNullOrEmpty("");   // 返回 true
string.IsNullOrEmpty(" ");  // 返回 false

 2.string.IsInterned

这个方法是用来检查字符串是否已经被字符串池(String Interning)处理过。字符串池是一种内存优化技术,用于存储静态字符串或常量字符串的单一副本,以减少内存使用。如果字符串已经被 interned,那么IsInterned返回那个字符串的 interned 版本;如果没有,则返回原字符串。

string a = "hello";
string b = "hello";
string c = new string('h', 5);
string.d(a) == string.d(b); // 返回 true,因为 a 和 b 指向同一个 interned 对象
string.d(a) == string.d(c); // 返回 false,因为 c 是一个新创建的字符串实例

3.string.IsNullOrWhiteSpace: 

这个方法用来检查字符串是否为null、空字符串或者只包含空白字符(如空格、制表符和换行符)。如果字符串满足这些条件之一,那么这个方法返回true

string.IsNullOrWhiteSpace(null);       // 返回 true
string.IsNullOrWhiteSpace("");        // 返回 true
string.IsNullOrWhiteSpace(" ");        // 返回 true
string.IsNullOrWhiteSpace("\t");      // 返回 true
string.IsNullOrWhiteSpace("\n");      // 返回 true
string.IsNullOrWhiteSpace("hello");    // 返回 false

 总结:

string.IsNullOrEmpty 只检查 null 和空字符串。

string.IsInterned 检查字符串是否已经被 interned。

string.IsNullOrWhiteSpace 检查 null、空字符串和空白字符。

http://www.lryc.cn/news/459654.html

相关文章:

  • 读书笔记 - 虚拟化技术 - 0 QEMU/KVM概述与历史
  • 常见的负载均衡
  • 利用sessionStorage收集用户访问信息,然后传递给后端
  • 什么是Qseven?模块电脑(核心板)规范标准简介二
  • leetcode数组(三)-有序数组的平方
  • HCIP-HarmonyOS Application Developer 习题(五)
  • 【详细教程】如何使用YOLOv11进行图像与视频的目标检测
  • H7-TOOL的LUA小程序教程第14期:任意波形信号发生器,0-20mA输出和微型数控电源(2024-10-11,已更新)
  • Redis面试篇3
  • 集成方案 | 借助 Microsoft Copilot for Sales 与 Docusign,加速销售流程!
  • k8s 1.28.2 集群部署 MinIO 分布式集群
  • HAL库常用的函数:
  • 如何捕捉行情爆发的前兆
  • 【万字长文】Word2Vec计算详解(一)CBOW模型
  • React Native源码学习
  • 【计网】从零开始认识https协议 --- 保证安全的网络通信
  • Ubuntu安装 MySQL【亲测有效】
  • Unity 从零开始搭建一套简单易用的UGUI小框架 扩展与优化篇(完结)
  • MySQL多表操作--外键约束多表关系
  • 【python入门到精通专题】8.装饰器
  • Halcon Blob分析提取小光斑
  • Lua
  • 模型 总观效应
  • 【HarmonyOS NEXT】实现页面水印功能
  • selenium自动化测试之Junit
  • 【氮化镓】基于氮化镓的互补逻辑集成电路[Nature Electronics]
  • Linux之如何找回 root 密码?
  • 后端参数校验方式
  • 访问控制列表(课内实验)
  • 处理Java内存溢出问题(java.lang.OutOfMemoryError):增加JVM堆内存与调优