404 Not Found

404 Not Found


nginx

字符串

声明与初始化

stringSystem.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,应在调用前检查长度。

📖 小节

📝 作业

  1. 声明一个字符串变量,使用插值语法输出 "我的名字是XXX,今年XX岁。"
  2. 编写程序:输入一个以逗号分隔的字符串 "a,b,c,d",用 Split 拆分后逐行输出每个元素
  3. 将字符串 " Hello World " 去除首尾空白后,把 "World" 替换为 "C#" 并输出结果
  4. 使用 StringBuilder 拼接从 1 到 100 的数字,每行一个,最后输出完整字符串
  5. 用逐字字符串定义一个 Windows 文件路径 C:\Program Files\MyApp\config.json 并输出
Web-Tutorial.com

Web-Tutorial 技术团队

由多位开发者共同维护的编程教程平台。每篇教程由对应领域的开发者编写和审核,确保内容准确可靠。如发现任何问题,欢迎向我们反馈。

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏