C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#字符串第x个字符位置插入字符

在C#中实现在字符串的第x个字符位置插入字符的常用方法

作者:Never_Satisfied

这篇文章主要介绍了在C#中6种在字符串第x个位置插入字符的方法,包括String.Insert()、Substring拼接、StringBuilder、字符数组、Span<T>和LINQ,并提供了性能比较和最佳实践,需要的朋友可以参考下

在C#中,有几种方法可以在字符串的第x个字符位置插入字符。以下是几种常用方法:

方法1:使用String.Insert()方法(最简洁)

// 在第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()拼接

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(适合多次插入)

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:转换为字符数组处理

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>(高性能)

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 方法

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个位置插入字符的扩展方法

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

处理多个插入点

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()方法:

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

选择哪种方法取决于具体需求:

到此这篇关于在C#中实现在字符串的第x个字符位置插入字符的常用方法的文章就介绍到这了,更多相关C#字符串第x个字符位置插入字符内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文