s.Remove(3, 2).Insert(3, "ZX");
-> Это не работает, если строка содержит символ Unicode, такой как Emojis.
С помощью в этом разделе я расширяю класс StringInfo на Replace by position, сохраняя Алгоритм Ник Миллер:
public static class StringInfoUtils { public static string ReplaceByPosition(this string str, string replaceBy, int offset, int count) { return new StringInfo(str).ReplaceByPosition(replaceBy, offset, count).String; } public static StringInfo ReplaceByPosition(this StringInfo str, string replaceBy, int offset, int count) { return str.RemoveByTextElements(offset, count).InsertByTextElements(offset, replaceBy); } public static StringInfo RemoveByTextElements(this StringInfo str, int offset, int count) { return new StringInfo(string.Concat( str.SubstringByTextElements(0, offset), offset + count < str.LengthInTextElements ? str.SubstringByTextElements(offset + count, str.LengthInTextElements - count - offset) : "" )); } public static StringInfo InsertByTextElements(this StringInfo str, int offset, string insertStr) { if (string.IsNullOrEmpty(str?.String)) return new StringInfo(insertStr); return new StringInfo(string.Concat( str.SubstringByTextElements(0, offset), insertStr, str.LengthInTextElements - offset > 0 ? str.SubstringByTextElements(offset, str.LengthInTextElements - offset) : "" )); } }