C#String安全替换

Ger*_*eel 3 c# string replace

你有什么想法或提示如何安全地更换字符串?

例:

string Example = "OK OR LOK";
Run Code Online (Sandbox Code Playgroud)

现在我想用true替换"OK",用false替换"LOK".

Example = Example.Replace("OK", "true");
Example = Example.Replace("LOK", "false");
Run Code Online (Sandbox Code Playgroud)

现在的结果是: Example = "true or Ltrue";

结果应该是: Example ="true or false";

我理解这个问题,但我不知道如何解决这个问题.

谢谢

Tim*_*ter 5

你可以用这种方法首先替换最长的字符串:

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;
}
Run Code Online (Sandbox Code Playgroud)

你的例子:

Example = ReplaceSafe(Example, new[] {new KeyValuePair<string, string>("OK", "true"), new KeyValuePair<string, string>("LOK", "false")});
Run Code Online (Sandbox Code Playgroud)