Wie können Sie Zeichenfolgen nur für einen Teil einer Zeichenfolge ersetzen?

Ich hätte gerne eine effiziente Methode, die in etwa so funktioniert

EDIT: Sorry, ich habe nicht gesagt, was ich vorher versucht hatte. Ich habe das Beispiel jetzt aktualisiert.

// 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

Der einzige Grund, den ich frage, ist, dass ich mir vorstellen würde, dass meine Implementierung mit Tausenden von Ersetzungen langsam wird.

Antworten auf die Frage(5)

Ihre Antwort auf die Frage