在C#中實現(xiàn)在字符串的第x個字符位置插入字符的常用方法
更新時間:2026年02月25日 08:40:17 作者:Never_Satisfied
這篇文章主要介紹了在C#中6種在字符串第x個位置插入字符的方法,包括String.Insert()、Substring拼接、StringBuilder、字符數(shù)組、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:轉換為字符數(shù)組處理
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開始計數(shù))插入字符
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
性能比較
String.Insert()- 最簡單,對于單次操作性能良好StringBuilder.Insert()- 適合多次插入操作Span<T>- 最高性能,但需要.NET Core 2.1+- 字符數(shù)組 - 中等性能,可讀性好
- LINQ - 最靈活但性能最差
注意事項
- 索引范圍:允許插入到字符串開頭(
index=0)和末尾(index=str.Length) - 空字符串處理:向空字符串插入字符會得到單個字符的字符串
- 性能考慮:避免在循環(huán)中使用字符串拼接,使用
StringBuilder
最佳實踐
對于大多數(shù)情況,推薦使用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
選擇哪種方法取決于具體需求:
- 簡單單次插入:使用
String.Insert() - 多次插入:使用
StringBuilder - 高性能要求:使用
Span<T> - 不可變和函數(shù)式風格:使用字符數(shù)組或LINQ
到此這篇關于在C#中實現(xiàn)在字符串的第x個字符位置插入字符的常用方法的文章就介紹到這了,更多相關C#字符串第x個字符位置插入字符內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C# 計算標準偏差相當于Excel中的STDEV函數(shù)實例
下面小編就為大家?guī)硪黄狢# 計算標準偏差相當于Excel中的STDEV函數(shù)實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01

