首页 > 编程笔记 > C#笔记 阅读:14

C# string字符串类型的用法(新手必看)

C# 中的字符串类型(System.String 类型的别名)表示不可变(创建之后即无法更改)的 Unicode 字符序列。字符串字面量应位于两个双引号之间:
string a = "Heat";

string 类型是引用类型而不是值类型,但是它的相等运算符却遵守值类型的语义:
string a = "test";
string b = "test";
Console.Write(a==b); //True

字符串中的转义字符和 char 字面量的转义字符是一致的:
string a = "Here's a tab:\t";
这意味着当需要一个反斜杠时,需要写两次才可以:
string a1 = "\\\\server\\fileshare\\helloworld.cs";
为避免这种情况,C# 引入了原意字符串字面量。原意字符串字面量要加@前缀,它不支持转义字符。

下面的原意字符串和之前的字符串是一样的:
string a1 = @"\\server\fileshare\helloworld.cs";
原意字符串可以贯穿多行:
string escaped = "First Line\r\nSecond Line";
string verbatim = @"First Line
Second Line";

// True if your text editor uses CR-LF line separators:
Console.WriteLine(escaped == verbatim);
原意字符串中需要用两个双引号来表示一个双引号字符:
string xml = @"<customer id=""123""></customer>";

C#字符串连接

+ 运算符可连接两个字符串:
string s = "a" + "b";

如果操作数之一是非字符串值,则会调用 ToString 方法将其转换为字符串:
string s = "a" + 5; //a5

重复使用 + 运算符来构建字符串是低效的。更好的解决方案是使用 System.Text.StringBuilder 类型。

C#字符串插值

$ 字符为前缀的字符串称为插值字符串。插值字符串可以在大括号内包含表达式:
int x = 4;
Console.Write($"A square has {x} sides");  // Prints: A square has 4 sides
大括号内可以是任意类型的合法 C# 表达式。C# 会调用 ToString 方法或等价方法将表达式转换为字符串。

如需更改表达式的格式,可以使用冒号,并附加格式字符串:
string s = $"255 in hex is {byte.MaxValue:X2}";  // X2 = 2-digit hexadecimal
// Evaluates to "255 in hex is FF"
如果代码中的冒号有其他用途(例如,三元条件运算符),则需要将整个表达式使用括号包裹起来:
bool b = true;
Console.WriteLine ($"The answer in binary is {(b ? 1 : 0)}");

插值字符串只能在单行内声明。如需在多行中声明字符串,请使用原意字符串运算符:
int x = 2;
// Note that $ must appear before @ prior to C# 8:
string s = $@"this interpolation spans {
x} lines";
若要在插值字符串中表示大括号,只需书写两个大括号字符即可。

C#常量字符串插值

从 C# 10 开始,如果字符串插值中的值为常量(字符串),则插值后的字符串仍然可以是常量:
const string greeting = "Hello";
const string message = $"{greeting}, world";

相关文章