在C#中是否有从字符串中删除特定索引的功能,例如:现在 s 是 "Ths is string"
string s = "This is string";
s.RemoveAt(2);
string s = "This is string";
s = s.Remove(2, 1);
输出: Ths is string
第一个参数
是要删除字符的起始索引
,第二个参数
是您想要删除的字符数
public static class MyStringExtensions
{
public static string RemoveAt(this string s, int index)
{
return s.Remove(index, 1);
}
}
用法:
string s = "This is string";
s = s.RemoveAt(2);
你也可以使用正则表达式。
Console.WriteLine(Regex.Replace("This is string", @"(?<=^.{2}).", ""));
string myString = "mon, ";
// Before it was mon,
myString = myString.Remove(3, 2);
// After it is mon
Remove()的第一个参数是开始删除的位置,第二个参数是要删除的字符数(包括在内)。
参考:https://learn.microsoft.com/en-us/dotnet/api/system.string.remove?view=net-7.0