在c#中,如何在字符串的第x个字符位置插入字符

在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

性能比较

  1. String.Insert() - 最简单,对于单次操作性能良好
  2. StringBuilder.Insert() - 适合多次插入操作
  3. Span<T> - 最高性能,但需要.NET Core 2.1+
  4. 字符数组 - 中等性能,可读性好
  5. LINQ - 最灵活但性能最差

注意事项

  1. 索引范围 :允许插入到字符串开头(index=0)和末尾(index=str.Length)
  2. 空字符串处理:向空字符串插入字符会得到单个字符的字符串
  3. 性能考虑 :避免在循环中使用字符串拼接,使用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
相关推荐
csbysj20201 小时前
jQuery UI 定制
开发语言
晔子yy2 小时前
AI编程时代:发挥Rules约束在Vibe-Coding的重要作用
开发语言·人工智能·后端
lly2024062 小时前
JavaScript 字符串深入解析
开发语言
码云数智-园园2 小时前
React Server Components 深度解析与实战应用:从原理到生产级落地指南
开发语言·前端·javascript
m0_531237172 小时前
C语言-while循环,continue/break,getchar()/putchar()
java·c语言·算法
kong79069282 小时前
SpringBoot原理
java·spring boot·后端
郝学胜-神的一滴2 小时前
Effective Modern C++ 条款38:线程句柄析构行为与Vibe Coding优化指南
开发语言·数据结构·c++·程序人生·多线程·并发
锅包一切2 小时前
【蓝桥杯JavaScript基础入门】二、JavaScript关键特性
开发语言·前端·javascript·学习·蓝桥杯
那我掉的头发算什么2 小时前
【图书管理系统】基于Spring全家桶的图书管理系统(下)
java·数据库·spring boot·后端·spring·mybatis