windows C#-字符串和字符串字面量(四)

Null 字符串和空字符串

空字符串是包含零个字符的 System.String 对象实例。 空字符串常用在各种编程方案中,表示空文本字段。 可以对空字符串调用方法,因为它们是有效的 System.String 对象。 对空字符串进行了初始化,如下所示:

string s = String.Empty;

相比较而言,null 字符串并不指 System.String 对象实例,只要尝试对 null 字符串调用方法,都会引发 NullReferenceException。 但是,可以在串联和与其他字符串的比较操作中使用 null 字符串。 以下示例说明了对 null 字符串的引用会引发和不会引发意外的某些情况:

string str = "hello";
string nullStr = null;
string emptyStr = String.Empty;

string tempStr = str + nullStr;
// Output of the following line: hello
Console.WriteLine(tempStr);

bool b = (emptyStr == nullStr);
// Output of the following line: False
Console.WriteLine(b);

// The following line creates a new empty string.
string newStr = emptyStr + nullStr;

// Null strings and empty strings behave differently. The following
// two lines display 0.
Console.WriteLine(emptyStr.Length);
Console.WriteLine(newStr.Length);
// The following line raises a NullReferenceException.
//Console.WriteLine(nullStr.Length);

// The null character can be displayed and counted, like other chars.
string s1 = "\x0" + "abc";
string s2 = "abc" + "\x0";
// Output of the following line: * abc*
Console.WriteLine("*" + s1 + "*");
// Output of the following line: *abc *
Console.WriteLine("*" + s2 + "*");
// Output of the following line: 4
Console.WriteLine(s2.Length);

使用 stringBuilder 快速创建字符串

.NET 中的字符串操作进行了高度的优化,在大多数情况下不会显著影响性能。 但是,在某些情况下(例如,执行数百次或数千次的紧密循环),字符串操作可能影响性能。 StringBuilder 类创建字符串缓冲区,用于在程序执行多个字符串操控时提升性能。 使用 StringBuilder 字符串,还可以重新分配各个字符,而内置字符串数据类型则不支持这样做。 例如,此代码更改字符串的内容,而无需创建新的字符串:

System.Text.StringBuilder sb = new System.Text.StringBuilder("Rat: the ideal pet");
sb[0] = 'C';
System.Console.WriteLine(sb.ToString());
//Outputs Cat: the ideal pet

在以下示例中,StringBuilder 对象用于通过一组数字类型创建字符串:

var sb = new StringBuilder();

// Create a string composed of numbers 0 - 9
for (int i = 0; i < 10; i++)
{
    sb.Append(i.ToString());
}
Console.WriteLine(sb);  // displays 0123456789

// Copy one character of the string (not possible with a System.String)
sb[0] = sb[9];

Console.WriteLine(sb);  // displays 9123456789

字符串、扩展方法和 LINQ

由于 String 类型实现 IEnumerable<T>,因此可以对字符串使用 Enumerable 类中定义的扩展方法。 为了避免视觉干扰,这些方法已从 String 类型的 IntelliSense 中排除,但它们仍然可用。 还可以使用字符串上的 LINQ 查询表达式。

相关推荐
赵瑽瑾5 分钟前
Lua语言的嵌入式系统
开发语言·后端·golang
霍璟琅6 分钟前
Delphi语言的数据可视化
开发语言·后端·golang
funsion8 分钟前
Lua中文语言编程源码-第十一节,其它小改动汉化过程
c语言·开发语言·中文分词·lua
User:你的影子24 分钟前
WPF进度条渲染
前端·javascript·c#·wpf
NPE~1 小时前
[渗透测试]热门搜索引擎推荐— — fofa篇
开发语言·搜索引擎·渗透测试·php·教程·软件推荐·fofa
霍熠烁1 小时前
Objective-C语言的云计算
开发语言·后端·golang
WANGWUSAN661 小时前
Python教程:使用Matplotlib模块画柱状图、饼形图、直方图
开发语言·经验分享·python·程序人生·matplotlib·数据可视化
饮长安千年月2 小时前
CVE-2024-13025-Codezips 大学管理系统 faculty.php sql 注入分析及拓展
开发语言·数据库·sql·网络安全·php
计算机视觉-Archer2 小时前
[NKU]C++安装环境 VScode
开发语言·c++
东方忘忧2 小时前
QT全局所有QSS样式实时切换
开发语言·数据库·qt