Skip to content

Instantly share code, notes, and snippets.

@danzuep
Created September 22, 2022 09:02
Show Gist options
  • Save danzuep/9c2f1f8de744c3f6af5f01726871427b to your computer and use it in GitHub Desktop.
Save danzuep/9c2f1f8de744c3f6af5f01726871427b to your computer and use it in GitHub Desktop.
public class StringExtensions
{
internal static string ReplaceFirstInstanceOf(this string? original, string oldValue, string newValue)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(original))
{
int index = original.IndexOf(oldValue);
result = index < 0 ? original : index == 0 ? string.Concat(newValue, original.AsSpan(oldValue.Length)) :
string.Concat(original.AsSpan(0, index), newValue, original.AsSpan(index + oldValue.Length));
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment