C# 添加字符串
最后修改于 2023 年 7 月 5 日
C# 添加字符串教程展示了如何在 C# 语言中添加字符串。
在 C# 中,字符串是 Unicode 字符的序列。
在 C# 中,有几种添加字符串的方法。
- + 运算符
- string.Concat 方法
- string.Join 方法
- StringBuilder Append 方法
- 字符串插值
- string.Format
C# 使用 + 运算符添加字符串
连接字符串最简单的方法是使用 + 或 += 运算符。 + 运算符既用于添加数字,也用于添加字符串; 在编程中,我们说该运算符被重载。
Program.cs
var a = "an old"; var b = " falcon"; var c = a + b; Console.WriteLine(a + b);
该示例使用 + 运算符添加两个字符串。
$ dotnet run an old falcon
在第二个示例中,我们使用了复合加法运算符。
Program.cs
var msg = "There are "; msg += "three falcons "; msg += "in the sky"; Console.WriteLine(msg);
该示例使用 += 运算符构建消息。
$ dotnet run There are three falcons in the sky
C# 使用 string.Concat 添加字符串
string.Concat 方法连接一个或多个字符串实例。
Program.cs
var a = "and old"; var b = " eagle"; var c = string.Concat(a, b); Console.WriteLine(c);
该示例使用 string.Concat 方法连接两个字符串。
C# 使用 string.Join 添加字符串
string.Join 方法连接指定数组的元素或集合的成员,并在每个元素或成员之间使用指定的分隔符。
Program.cs
var words = new List<string>{"There", "are", "two", "owls", "on", "the", "tree"};
var msg = string.Join(" ", words);
Console.WriteLine(msg);
在该示例中,我们连接列表中的字符串。
$ dotnet run There are two owls on the tree
C# 使用 StringBuilder 添加字符串
StringBuilder 是一个可变的字符序列。 它的 Append 方法将指定的字符串追加到字符串实例。
Program.cs
using System.Text;
var builder = new StringBuilder("There");
builder.Append(" are");
builder.Append(" two");
builder.Append(" falcons");
builder.Append(" in");
builder.Append(" the");
builder.Append(" sky");
Console.WriteLine(builder);
在该示例中,我们使用 StringBuilder 形成一个新字符串。
$ dotnet run There are two falcons in the sky
C# 使用字符串插值添加字符串
我们可以使用字符串插值来构建 C# 字符串。 插值字符串以 $ 字符开头。
Program.cs
var w1 = "three";
var w2 = "owls";
var msg = $"There are {w1} {w2} on the tree";
Console.WriteLine(msg);
在插值字符串中,花括号 {} 内的变量会被展开。
$ dotnet run There are three owls on the tree
C# 使用 string.Format 添加字符串
string.Format 基于指定的格式将对象的值转换为字符串,并将它们插入到新形成的字符串中。
Program.cs
var w1 = "three";
var w2 = "owls";
var msg = string.Format("There are {0} {1} on the tree", w1, w2);
Console.WriteLine(msg);
我们使用 string.Format 构建一个新字符串。
来源
在本文中,我们展示了几种在 C# 中添加字符串的方法。
作者
列出所有 C# 教程。