gpt4 book ai didi

C# 字符串安全替换

转载 作者:行者123 更新时间:2023-11-30 13:25:44 24 4
gpt4 key购买 nike

对于如何安全地替换字符串,您有什么想法或技巧吗?

例子:

string Example = "OK OR LOK";

现在我想用 true 替换“OK”,用 false 替换“LOK”。

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

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

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

我明白这个问题,但我不知道如何解决这个问题。

谢谢

最佳答案

你可以先替换最长的字符串,f.e.用这个方法:

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;
}

你的例子:

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

关于C# 字符串安全替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41036227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com