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

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

1.string.IsNullOrEmpty

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

cs 复制代码
string.IsNullOrEmpty(null); // 返回 true
string.IsNullOrEmpty("");   // 返回 true
string.IsNullOrEmpty(" ");  // 返回 false

2.string.IsInterned

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

cs 复制代码
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

cs 复制代码
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、空字符串和空白字符。

相关推荐
明月看潮生2 小时前
青少年编程与数学 02-019 Rust 编程基础 05课题、复合数据类型
开发语言·青少年编程·rust·编程与数学
幼稚诠释青春2 小时前
Java学习笔记(对象)
java·开发语言
XYR1212122 小时前
C# 参数
c#
Wyc724093 小时前
JDBC:java与数据库连接,Maven,MyBatis
java·开发语言·数据库
强化学习与机器人控制仿真3 小时前
Newton GPU 机器人仿真器入门教程(零)— NVIDIA、DeepMind、Disney 联合推出
开发语言·人工智能·python·stm32·深度学习·机器人·自动驾驶
oMMh3 小时前
使用C# ASP.NET创建一个可以由服务端推送信息至客户端的WEB应用(2)
前端·c#·asp.net
Risehuxyc3 小时前
GrassRoot备份项目
c#
芯片SIPI设计3 小时前
MIPI C-PHY 标准学习----一种通用多信号传输方案
c语言·开发语言·学习
Tiny番茄4 小时前
No module named ‘xxx’报错原因及解决方式
开发语言·python
咩咩觉主4 小时前
c#数据结构 线性表篇 非常用线性集合总结
开发语言·数据结构·unity·c#·游戏引擎·程序框架