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
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")});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With