C# String.Replace with a start/index (Added my (slow) implementation)

Posted by Chris T on Stack Overflow See other posts from Stack Overflow or by Chris T
Published on 2010-01-18T15:43:40Z Indexed on 2010/03/12 13:37 UTC
Read the original article Hit count: 299

I'd like an efficient method that would work something like this

EDIT: Sorry I didn't put what I'd tried before. I updated the example now.

// Method signature, Only replaces first instance or how many are specified in max
public int MyReplace(ref string source,string org, string replace, int start, int max)
{
     int ret = 0;
     int len = replace.Length;
     int olen = org.Length;
     for(int i = 0; i < max; i++)
     {
          // Find the next instance of the search string
          int x = source.IndexOf(org, ret + olen);
          if(x > ret)
             ret = x;
          else
             break;

         // Insert the replacement
         source = source.Insert(x, replace);
         // And remove the original
         source = source.Remove(x + len, olen); // removes original string
     }
     return ret;
}

string source = "The cat can fly but only if he is the cat in the hat";
int i = MyReplace(ref source,"cat", "giraffe", 8, 1); 

// Results in the string "The cat can fly but only if he is the giraffe in the hat"
// i contains the index of the first letter of "giraffe" in the new string

The only reason I'm asking is because my implementation I'd imagine getting slow with 1,000s of replaces.

© Stack Overflow or respective owner

Related posts about c#

Related posts about string-manipulation