字符串
声明与初始化
string 是 System.String 的别名,属于不可变的引用类型。字符串一经创建,其内容无法修改。
示例
CSHARP
string name = "Hello";
string empty = "";
string nullStr = null;
string fromChar = new string('A', 5);
Console.WriteLine(name);
Console.WriteLine(fromChar);
TEXT
Hello
AAAAA
字符串不可变性
字符串对象一旦创建,其中的字符序列就不能被改变。所有"修改"操作都会返回一个新字符串,原字符串保持不变。
示例
CSHARP
string a = "Hello";
string b = a;
a = a + " World";
Console.WriteLine(a);
Console.WriteLine(b);
TEXT
Hello World
Hello
💡 b 仍然指向原始的 "Hello",a + " World" 产生了一个全新的字符串对象。
字符串拼接
使用 + 运算符、String.Concat() 或 String.Join() 可以将多个字符串连接在一起。
示例
CSHARP
string s1 = "Hello" + " " + "World";
string s2 = String.Concat("A", "B", "C");
string s3 = String.Join(", ", new string[] { "apple", "banana", "cherry" });
Console.WriteLine(s1);
Console.WriteLine(s2);
Console.WriteLine(s3);
TEXT
Hello World
ABC
apple, banana, cherry
字符串插值
使用 $"" 插值语法或 String.Format() 将变量嵌入字符串。
示例
CSHARP
string name = "Alice";
int age = 25;
string s1 = $"My name is {name}, age {age}.";
string s2 = String.Format("My name is {0}, age {1}.", name, age);
string s3 = $"2 + 3 = {2 + 3}";
Console.WriteLine(s1);
Console.WriteLine(s2);
Console.WriteLine(s3);
TEXT
My name is Alice, age 25.
My name is Alice, age 25.
2 + 3 = 5
💡 插值表达式 {} 内可以写任意 C# 表达式,也可加格式说明,如 {value:F2}。
字符串比较
== 对字符串执行值相等比较(而非引用比较)。Equals()、Compare() 和 CompareOrdinal() 提供更精细的控制。
示例
CSHARP
string a = "hello";
string b = "hello";
string c = "HELLO";
Console.WriteLine(a == b);
Console.WriteLine(a.Equals(b));
Console.WriteLine(String.Compare(a, c, StringComparison.OrdinalIgnoreCase) == 0);
Console.WriteLine(String.CompareOrdinal(a, c) > 0);
TEXT
True
True
True
True
⚠️ 字符串的 == 比较的是值,不是引用,这与一般引用类型不同。
常用方法:Length / Substring / Replace / Split
这些方法是日常字符串操作中使用频率最高的。
示例
CSHARP
string s = "Hello, World!";
Console.WriteLine(s.Length);
Console.WriteLine(s.Substring(7));
Console.WriteLine(s.Substring(0, 5));
Console.WriteLine(s.Replace("World", "C#"));
string parts = "a,b,c";
foreach (string p in parts.Split(','))
{
Console.WriteLine(p);
}
TEXT
13
World!
Hello
Hello, C#!
a
b
c
常用方法:Trim / Contains / Index
Trim() 去除首尾空白,Contains() 判断子串是否存在,IndexOf() / LastIndexOf() 查找位置。
示例
CSHARP
string s = " Hello World ";
Console.WriteLine($"[{s.Trim()}]");
Console.WriteLine(s.Contains("World"));
Console.WriteLine(s.IndexOf("World"));
Console.WriteLine(s.LastIndexOf("o"));
TEXT
[Hello World]
True
8
7
常用方法:大小写 / StartsWith / EndsWith / Pad / Remove / Insert
更多实用的字符串处理方法。
示例
CSHARP
string s = "Hello";
Console.WriteLine(s.ToUpper());
Console.WriteLine(s.ToLower());
Console.WriteLine(s.StartsWith("Hel"));
Console.WriteLine(s.EndsWith("llo"));
Console.WriteLine("5".PadLeft(3, '0'));
Console.WriteLine("5".PadRight(3, '0'));
string r = "Hello World".Remove(5);
Console.WriteLine(r);
string ins = "H World".Insert(1, "ello");
Console.WriteLine(ins);
TEXT
HELLO
hello
True
True
005
500
Hello
Hello World
逐字字符串与原始字符串
逐字字符串 @"" 不处理转义序列,适合文件路径。C# 11 引入原始字符串 """ 支持多行且无需转义。
示例
CSHARP
string path = @"C:\Users\Doc\file.txt";
string json = """
{
"name": "Alice",
"age": 25
}
""";
Console.WriteLine(path);
Console.WriteLine(json.Trim());
TEXT
C:\Users\Doc\file.txt
{
"name": "Alice",
"age": 25
}
📌 逐字字符串中 " 用 "" 表示,原始字符串以至少三个引号开头和结尾。
StringBuilder 简介
在循环中反复拼接字符串时,string 每次都创建新对象,性能较差。StringBuilder 在内部缓冲区操作,拼接完成后一次性生成字符串。
示例
CSHARP
using System.Text;
var sb = new StringBuilder();
for (int i = 0; i < 5; i++)
{
sb.Append(i);
sb.Append(" ");
}
Console.WriteLine(sb.ToString().Trim());
TEXT
0 1 2 3 4
🔥 循环拼接大量字符串时,优先选择 StringBuilder,可显著减少内存分配。
字符编码
C# 字符串采用 UTF-16 编码,char 占 2 个字节(一个 UTF-16 码元)。
示例
CSHARP
char ch = '中';
Console.WriteLine(ch);
Console.WriteLine((int)ch);
Console.WriteLine(sizeof(char));
TEXT
中
20013
2
❓ 常见问题
Q 字符串用
== 比较的是引用还是值?A 值。字符串的
== 运算符已被重载,执行内容相等比较。Q 为什么循环拼接字符串要用 StringBuilder?
A 因为
string 不可变,每次拼接都创建新对象;StringBuilder 在缓冲区中修改,最后才生成一个字符串。Q 逐字字符串
@"" 和普通字符串有什么区别?A 逐字字符串不处理转义字符(如
\n、\t),反斜杠直接保留,适合写文件路径和正则表达式。Q
Substring 越界会怎样?A 抛出
ArgumentOutOfRangeException,应在调用前检查长度。📖 小节
string是不可变引用类型,string是System.String的别名- 拼接方式:
+、String.Concat()、String.Join() - 插值方式:
$""和String.Format() - 比较:
==比较值,Equals()、Compare()提供更多选项 - 常用方法:
Length、Substring、Replace、Split、Trim、Contains、IndexOf、ToUpper、ToLower、StartsWith、EndsWith、PadLeft、PadRight、Remove、Insert - 逐字字符串
@""不转义,原始字符串"""用于多行 StringBuilder适合循环拼接场景,提升性能- 字符串使用 UTF-16 编码,
char占 2 字节
📝 作业
- 声明一个字符串变量,使用插值语法输出
"我的名字是XXX,今年XX岁。" - 编写程序:输入一个以逗号分隔的字符串
"a,b,c,d",用Split拆分后逐行输出每个元素 - 将字符串
" Hello World "去除首尾空白后,把"World"替换为"C#"并输出结果 - 使用
StringBuilder拼接从 1 到 100 的数字,每行一个,最后输出完整字符串 - 用逐字字符串定义一个 Windows 文件路径
C:\Program Files\MyApp\config.json并输出



