欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 锐评 > C# 字符串(string)三个不同的处理方法:IsNullOrEmpty、IsInterned 、IsNullOrWhiteSpace

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

2024/10/25 20:23:13 来源:https://blog.csdn.net/2302_77639120/article/details/142794712  浏览:    关键词: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、空字符串和空白字符。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com