Skip to content

Instantly share code, notes, and snippets.

@ericnewton76
Last active December 20, 2015 07:19
Show Gist options
  • Save ericnewton76/6091998 to your computer and use it in GitHub Desktop.
Save ericnewton76/6091998 to your computer and use it in GitHub Desktop.
An extension to StringBuilder for ReplaceAt functionality. Given an index, and optional length, and a string to overwrite, this method overwrites an area of characters.
namespace System.Text
{
internal static class StringBuilderExtensions
{
#if EXTENSIONS_SUPPORTED
public static StringBuilder ReplaceAt(this StringBuilder sb, string value, int index, int count)
{
return StringBuilderExtensions.ReplaceAt(sb, value, index, count);
}
#endif
public static StringBuilder ReplaceAt(StringBuilder sb, int index, int length, string value)
{
if (string.IsNullOrEmpty(value))
{
sb.Remove(index, length);
}
else
{
if (index + length > sb.Length)
throw new ArgumentException(string.Format("Given the index of '{0}' and length of '{1}', the replacement area extends beyond the length of the string.", index, length));
if (value.Length > length)
{
sb.Insert(index, new String('#',value.Length-length));
}
if (value.Length < length)
{
sb.Remove(index + value.Length, length - value.Length);
}
for (int i = index, j = 0; j < value.Length; i++, j++)
{
sb[i] = value[j];
}
}
return sb;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment