Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# String Replace safely

Tags:

string

c#

replace

do you have any ideas or tips how to replace a string safely?

Example:

string Example = "OK OR LOK";

Now i want to replace "OK" with true and "LOK" with false.

Example = Example.Replace("OK", "true");
Example = Example.Replace("LOK", "false");

Now the Result is: Example = "true or Ltrue";

The Result should be: Example ="true or false";

I understand the problem, but i have no idea how to fix this.

Thanks

like image 835
Gerry Seel Avatar asked Dec 08 '22 20:12

Gerry Seel


1 Answers

You could replace the longest strings first, f.e. with this method:

public static string ReplaceSafe(string str, IEnumerable<KeyValuePair<string, string>>  replaceAllOfThis)
{
    foreach (var kv in replaceAllOfThis.OrderByDescending(kv => kv.Key.Length))
    {
        str = str.Replace(kv.Key, kv.Value);
    }
    return str;
}

Your example:

Example = ReplaceSafe(Example, new[] {new KeyValuePair<string, string>("OK", "true"), new KeyValuePair<string, string>("LOK", "false")});
like image 114
Tim Schmelter Avatar answered Dec 22 '22 18:12

Tim Schmelter