C# 字符串(String)

不可变性、常用方法、`StringBuilder`、以及比较与格式化。

Beginner
Key Points`string` 不可变,每次「修改」都产生新对象;频繁拼接用 `StringBuilder`。

不可变性

C#
string s = "hello";
string t = s.ToUpper();       // 产生新字符串,s 不变

Console.WriteLine(s);
Console.WriteLine(t);
Console.WriteLine(object.ReferenceEquals(s, t));

// 每次 += 都新建一个字符串
string r = "";
for (int i = 0; i < 3; i++)
{
    r += i;
}
Console.WriteLine(r);
Output
hello
HELLO
False
012

Concatenating with += N times creates N temporary strings — O(n²). One of the classic C# performance traps.

StringBuilder

C#
using System.Text;

var sb = new StringBuilder();
for (int i = 0; i < 5; i++)
{
    sb.Append(i).Append(',');
}
Console.WriteLine(sb.ToString());

sb.Insert(0, "数字:");
sb.Replace(",", " ");
Console.WriteLine(sb.ToString().TrimEnd());

Console.WriteLine(sb.Length);
Output
0,1,2,3,4,
数字:0 1 2 3 4
14

StringBuilder keeps a mutable buffer; Append allocates nothing new. Rule of thumb: switch once you concatenate more than 5–10 times.

常用方法

C#
string s = "  Hello, World  ";

Console.WriteLine($"[{s.Trim()}]");
Console.WriteLine(s.Trim().ToUpper());
Console.WriteLine(s.Trim().ToLower());
Console.WriteLine(s.Trim().Length);
Console.WriteLine(s.Contains("World"));
Console.WriteLine(s.Trim().StartsWith("Hello"));
Console.WriteLine(s.Trim().Replace("World", "C#"));
Console.WriteLine(s.Trim().Substring(0, 5));
Console.WriteLine(string.Join("|", s.Trim().Split(", ")));
Output
[Hello, World]
HELLO, WORLD
hello, world
12
True
True
Hello, C#
Hello
Hello|World
MethodEffect
Trim / TrimStart / TrimEnd去空白
Split按分隔符拆成数组
Join把数组拼成字符串
Substring取子串
Replace替换
IndexOf / LastIndexOf查找位置,找不到返回 -1
PadLeft / PadRight补齐
IsNullOrEmpty / IsNullOrWhiteSpace判空

比较

C#
string a = "Hello";
string b = "hello";

Console.WriteLine(a == b);                                    // False,区分大小写
Console.WriteLine(string.Equals(a, b, StringComparison.OrdinalIgnoreCase));
Console.WriteLine(a.CompareTo(b));
Console.WriteLine(string.Compare(a, b, StringComparison.OrdinalIgnoreCase));
Output
False
True
-1
0
== on string compares values (it is overloaded) while object.ReferenceEquals compares references. For sorting and lookups, passing StringComparison.Ordinal is much faster than culture-aware comparison.

插值与格式化

C#
var name = "张三";
var score = 92.567;

Console.WriteLine($"姓名:{name},分数:{score:F1}");
Console.WriteLine($"补零:{42:D5}");
Console.WriteLine($"十六进制:{255:X}");
Console.WriteLine($"百分比:{0.856:P1}");
Console.WriteLine($"金额:{1234.5m:C}");
Console.WriteLine($"对齐:|{name,-6}|{name,6}|");
Output
姓名:张三,分数:92.6
补零:00042
十六进制:FF
百分比:85.6%
金额:¥1,234.50
对齐:|张三    |  张三|

In {value:format} the part after the colon is the format: F1 one decimal, D5 five digits zero-padded, X hex, P1 percent, C currency. A comma plus a signed number sets width and alignment.

Friends & Partners