August 8, 2022

String Replace with StringComparison

I found this https://stackoverflow.com/questions/244531/is-there-an-alternative-to-string-replace-that-is-case-insensitive/13847351#comment31063745_244933 I added a few defensive checks.
public static string Replace(
    this string src,
    string oldValue,
    string newValue,
    StringComparison comparison)
{
    if (string.IsNullOrEmpty(oldValue))
        throw new ArgumentException("String cannot be of zero length or null.", "oldValue");
        
    if (string.IsNullOrEmpty(newValue)) // It can be an empty string though
        throw new ArgumentException("String cannot be null.", "newValue");

    // skip the loop entirely if oldValue and newValue are the same
    if (string.Compare(oldValue, newValue, comparison) == 0)
        return src;

    if (oldValue.Length > src.Length)
        return src;

    int index = src.IndexOf(oldValue, comparison);
    if (index == -1)
        return src;

    var sb = new StringBuilder(src.Length);

    int previousIndex = 0;

    while (index != -1)
    {
        sb.Append(src.Substring(previousIndex, index - previousIndex));
        sb.Append(newValue);
        index += oldValue.Length;

        previousIndex = index;
        index = src.IndexOf(oldValue, index, comparison);
    }

    sb.Append(src.Substring(previousIndex));

    return sb.ToString();
}

No comments: