Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static string ReplaceSubstring(this string s, string replacement, int startIndex, int length)
- {
- if (s == null)
- throw new ArgumentNullException("s", "Input string cannot be null");
- else if (startIndex < 0)
- throw new ArgumentOutOfRangeException("startIndex", "startIndex cannot be negative");
- else if (length < 0)
- throw new ArgumentOutOfRangeException("length", "length cannot be negative");
- var endIndex = startIndex + length;
- int index = 0, actualFrom = 0, actualTo = 0;
- var foundFrom = false;
- foreach (var c in s)
- {
- if (index == endIndex)
- break;
- else if (index == startIndex)
- foundFrom = true;
- if (!char.IsHighSurrogate(c))
- index++;
- if (!foundFrom)
- actualFrom++;
- actualTo++;
- }
- if (startIndex > index)
- throw new ArgumentOutOfRangeException("startIndex", $"\"startIndex\" argument is outside string boundaries: {startIndex} > {index}");
- else if (endIndex > index)
- throw new ArgumentOutOfRangeException("length", $"\"length\" argument is outside string boundaries: {endIndex} > {index}");
- return string.Concat(
- s.Substring(0, actualFrom),
- replacement,
- s.Substring(actualTo));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement