在C#中實(shí)現(xiàn)在字符串的第x個(gè)字符位置插入字符的常用方法
在C#中,有幾種方法可以在字符串的第x個(gè)字符位置插入字符。以下是幾種常用方法:
方法1:使用String.Insert()方法(最簡(jiǎn)潔)
// 在第x個(gè)位置插入字符(索引從0開(kāi)始) string str = "HelloWorld"; int x = 5; // 插入位置索引 char ch = ' '; // 要插入的字符 string result = str.Insert(x, ch.ToString()); Console.WriteLine(result); // 輸出: Hello World // 如果要插入的位置從1開(kāi)始(人類(lèi)可讀) int x_human = 6; // 第6個(gè)位置 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:轉(zhuǎn)換為字符數(shù)組處理
string str = "HelloWorld"; int x = 5; char ch = ' '; char[] original = str.ToCharArray(); char[] newChars = new char[original.Length + 1]; // 復(fù)制x之前的字符 Array.Copy(original, 0, newChars, 0, x); // 插入新字符 newChars[x] = ch; // 復(fù)制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個(gè)位置插入字符的擴(kuò)展方法
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到字符串長(zhǎng)度之間");
return str.Insert(index, ch.ToString());
}
// 方法2:在指定位置(從1開(kāi)始計(jì)數(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
處理多個(gè)插入點(diǎn)
string str = "1234567890";
// 在第3位和第7位插入分隔符
StringBuilder sb = new StringBuilder(str);
// 注意:從后往前插入,避免索引變化
sb.Insert(7, '-'); // 第8個(gè)位置
sb.Insert(3, '-'); // 第4個(gè)位置
Console.WriteLine(sb.ToString()); // 輸出: 123-4567-890
// 或者使用擴(kuò)展方法
var insertions = new[] { (3, '-'), (7, '-') };
string result = str.InsertCharsAt(insertions);
Console.WriteLine(result); // 輸出: 123-4567-890
性能比較
String.Insert()- 最簡(jiǎn)單,對(duì)于單次操作性能良好StringBuilder.Insert()- 適合多次插入操作Span<T>- 最高性能,但需要.NET Core 2.1+- 字符數(shù)組 - 中等性能,可讀性好
- LINQ - 最靈活但性能最差
注意事項(xiàng)
- 索引范圍:允許插入到字符串開(kāi)頭(
index=0)和末尾(index=str.Length) - 空字符串處理:向空字符串插入字符會(huì)得到單個(gè)字符的字符串
- 性能考慮:避免在循環(huán)中使用字符串拼接,使用
StringBuilder
最佳實(shí)踐
對(duì)于大多數(shù)情況,推薦使用String.Insert()方法:
public static string InsertCharacter(string original, int position, char character)
{
// 驗(yàn)證輸入
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
選擇哪種方法取決于具體需求:
- 簡(jiǎn)單單次插入:使用
String.Insert() - 多次插入:使用
StringBuilder - 高性能要求:使用
Span<T> - 不可變和函數(shù)式風(fēng)格:使用字符數(shù)組或LINQ
到此這篇關(guān)于在C#中實(shí)現(xiàn)在字符串的第x個(gè)字符位置插入字符的常用方法的文章就介紹到這了,更多相關(guān)C#字符串第x個(gè)字符位置插入字符內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C# 計(jì)算標(biāo)準(zhǔn)偏差相當(dāng)于Excel中的STDEV函數(shù)實(shí)例
下面小編就為大家?guī)?lái)一篇C# 計(jì)算標(biāo)準(zhǔn)偏差相當(dāng)于Excel中的STDEV函數(shù)實(shí)例。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-01-01
C#程序員應(yīng)該養(yǎng)成的程序性能優(yōu)化寫(xiě)法
工作和生活中經(jīng)常可以看到一些程序猿,寫(xiě)代碼的時(shí)候只關(guān)注代碼的邏輯性,而不考慮運(yùn)行效率,其實(shí)這對(duì)大多數(shù)程序猿來(lái)說(shuō)都是沒(méi)有問(wèn)題的,不過(guò)作為一只有理想的CodeMonkey,我還是希望給大家分享一些性能優(yōu)化心得2017-08-08
C#實(shí)現(xiàn)簡(jiǎn)單的計(jì)算器功能(窗體)
這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)簡(jiǎn)單的計(jì)算器功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01
DataGridView控件顯示行號(hào)的正確代碼及分析
今天要用到DataGridView,想給它動(dòng)態(tài)的顯示行號(hào)。于是在網(wǎng)上找了一下解決方法。結(jié)果發(fā)現(xiàn)了不少問(wèn)題。然而就是這么一段有錯(cuò)的代碼,幾乎充斥著整個(gè)互聯(lián)網(wǎng),千篇一律的COPY,沒(méi)有一個(gè)人糾正2013-08-08

