I want to take and edit a string in-place in a .NET app. I know that StringBuilder allows me to do in-place appends, inserts, and replaces, but it does not allow an easy way of doing stuff like this:
while (script.IndexOf("@Unique", StringComparison.InvariantCultureIgnoreCase) != -1)
{
int Location = script.IndexOf("@Unique", StringComparison.InvariantCultureIgnoreCase);
script = script.Remove(Location, 7);
script = script.Insert(Location, Guid.NewGuid().ToString());
}
As there is no IndexOf in StringBuilder. Does anyone have an effective way to do in-place editing of textual information?
Edit #1:
Changed sample to make more obvious that each ‘replace’ needs to have a different result.
If your code really is this straightforward then why not just use one of the built-in
Replacemethods, either onstring,StringBuilderorRegex?EDIT FOLLOWING COMMENT…
You can replace each occurrence with a separate value by using one of the overloads of
Regex.Replacethat takes aMatchEvaluatorargument: