D.R.
D.R.

Reputation: 21224

Replace multiple ranges in a string

I want to replace multiple ranges in a string, e.g.:

Original string: "My XXX XXX is Y"
Range 1: Start=3, Length=3, Replacement=house
Range 2: Start=14, Length=1, Replacement=big

Desired output: "My house XXX is big"

How to do that with .NET and C#? I tried to replace one range at a time, however, this ruins the indices if the replacement string has a different length than its range. I only know of the indices and replaced strings in ranges are not unique. Do I really have to manually update all those indices all the time or is there a built-in way to do that?

Upvotes: 2

Views: 672

Answers (2)

svick
svick

Reputation: 244928

One approach would be build the result piece by piece into a StringBuilder. That way, you have the original string at hand the whole time, so you can use the original indexes:

static string ReplaceRanges(string original, IEnumerable<Range> ranges)
{
    var result = new StringBuilder(original.Length);

    int index = 0;

    foreach (var range in ranges)
    {
        result.Append(original, index, range.Start - index);

        result.Append(range.Replacement);

        index = range.Start + range.Length;
    }

    result.Append(original, index, original.Length - index);

    return result.ToString();
}

A slight modification of this approach would be to precompute the length of the final string based on the ranges. This would minimize unnecessary allocations, which could be important if you have many ranges.

Upvotes: 0

jjaskulowski
jjaskulowski

Reputation: 2564

Please perform replacements starting from the last index - from right-most string to left-most. Now you don't need to update any indices. It's that easy.

Upvotes: 4

Related Questions