在C#中,有几种方法可以在字符串的第x个字符位置插入字符。以下是几种常用方法:
方法1:使用 String.Insert() 方法(最简洁)
csharp
// 在第x个位置插入字符(索引从0开始)
string str = "HelloWorld";
int x = 5; // 插入位置索引
char ch = ' '; // 要插入的字符
string result = str.Insert(x, ch.ToString());
Console.WriteLine(result); // 输出: Hello World
// 如果要插入的位置从1开始(人类可读)
int x_human = 6; // 第6个位置
string result2 = str.Insert(x_human - 1, ch.ToString());
Console.WriteLine(result2); // 输出: Hello World
方法2:使用 Substring() 拼接
csharp
string str = "HelloWorld";
int x = 5;
char ch = ' ';
// 取x之前的部分 + 插入的字符 + x之后的部分
string result = str.Substring(0, x) + ch + str.Substring(x);
Console.WriteLine(result); // 输出: Hello World
方法3:使用 StringBuilder(适合多次插入)
csharp
using System.Text;
string str = "HelloWorld";
int x = 5;
char ch = ' ';
StringBuilder sb = new StringBuilder(str);
sb.Insert(x, ch);
string result = sb.ToString();
Console.WriteLine(result); // 输出: Hello World
方法4:转换为字符数组处理
csharp
string str = "HelloWorld";
int x = 5;
char ch = ' ';
char[] original = str.ToCharArray();
char[] newChars = new char[original.Length + 1];
// 复制x之前的字符
Array.Copy(original, 0, newChars, 0, x);
// 插入新字符
newChars[x] = ch;
// 复制x之后的字符
Array.Copy(original, x, newChars, x + 1, original.Length - x);
string result = new string(newChars);
Console.WriteLine(result); // 输出: Hello World
方法5:使用 Span<T>(高性能)
csharp
string str = "HelloWorld";
int x = 5;
char ch = ' ';
Span<char> buffer = new char[str.Length + 1];
str.AsSpan(0, x).CopyTo(buffer);
buffer[x] = ch;
str.AsSpan(x).CopyTo(buffer.Slice(x + 1));
string result = new string(buffer);
Console.WriteLine(result); // 输出: Hello World
方法6:LINQ 方法
csharp
using System.Linq;
string str = "HelloWorld";
int x = 5;
char ch = ' ';
string result = new string(str
.SelectMany((c, index) => index == x ? new[] { ch, c } : new[] { c })
.ToArray());
// 或者在末尾插入的情况
if (x == str.Length)
{
result = str + ch;
}
Console.WriteLine(result); // 输出: Hello World
完整示例:在第x个位置插入字符的扩展方法
csharp
public static class StringExtensions
{
// 方法1:在指定索引位置插入字符
public static string InsertCharAt(this string str, int index, char ch)
{
if (string.IsNullOrEmpty(str))
return ch.ToString();
if (index < 0 || index > str.Length)
throw new ArgumentOutOfRangeException(nameof(index),
"索引必须在0到字符串长度之间");
return str.Insert(index, ch.ToString());
}
// 方法2:在指定位置(从1开始计数)插入字符
public static string InsertCharAtPosition(this string str, int position, char ch)
{
return InsertCharAt(str, position - 1, ch);
}
// 方法3:批量插入字符
public static string InsertCharsAt(this string str, IEnumerable<(int index, char ch)> insertions)
{
var sorted = insertions.OrderByDescending(x => x.index);
StringBuilder sb = new StringBuilder(str);
foreach (var (index, ch) in sorted)
{
if (index >= 0 && index <= sb.Length)
sb.Insert(index, ch);
}
return sb.ToString();
}
}
// 使用示例
string text = "HelloWorld";
Console.WriteLine(text.InsertCharAt(5, ' ')); // 输出: Hello World
Console.WriteLine(text.InsertCharAt(0, '!')); // 输出: !HelloWorld
Console.WriteLine(text.InsertCharAt(text.Length, '!')); // 输出: HelloWorld!
Console.WriteLine(text.InsertCharAtPosition(6, ' ')); // 输出: Hello World
处理多个插入点
csharp
string str = "1234567890";
// 在第3位和第7位插入分隔符
StringBuilder sb = new StringBuilder(str);
// 注意:从后往前插入,避免索引变化
sb.Insert(7, '-'); // 第8个位置
sb.Insert(3, '-'); // 第4个位置
Console.WriteLine(sb.ToString()); // 输出: 123-4567-890
// 或者使用扩展方法
var insertions = new[] { (3, '-'), (7, '-') };
string result = str.InsertCharsAt(insertions);
Console.WriteLine(result); // 输出: 123-4567-890
性能比较
String.Insert()- 最简单,对于单次操作性能良好StringBuilder.Insert()- 适合多次插入操作Span<T>- 最高性能,但需要.NET Core 2.1+- 字符数组 - 中等性能,可读性好
- LINQ - 最灵活但性能最差
注意事项
- 索引范围 :允许插入到字符串开头(
index=0)和末尾(index=str.Length) - 空字符串处理:向空字符串插入字符会得到单个字符的字符串
- 性能考虑 :避免在循环中使用字符串拼接,使用
StringBuilder
最佳实践
对于大多数情况,推荐使用String.Insert()方法:
csharp
public static string InsertCharacter(string original, int position, char character)
{
// 验证输入
if (string.IsNullOrEmpty(original))
return character.ToString();
// 确保位置有效
position = Math.Max(0, Math.Min(position, original.Length));
// 插入字符
return original.Insert(position, character.ToString());
}
// 使用示例
string phoneNumber = "1234567890";
string formatted = InsertCharacter(InsertCharacter(phoneNumber, 3, '-'), 7, '-');
Console.WriteLine(formatted); // 输出: 123-456-7890
选择哪种方法取决于具体需求:
- 简单单次插入:使用
String.Insert() - 多次插入:使用
StringBuilder - 高性能要求:使用
Span<T> - 不可变和函数式风格:使用字符数组或LINQ