【发布时间】:2017-11-29 02:03:12
【问题描述】:
只要现有的String 包含以下字符之一,我想将特定的String 添加到现有的String 中:=、+、-、* 或/ .
例如,我想将String "test" 添加到现有的String 中:
"=ABC+DEF"
结果 String 应该是:“=testABC+testDEF”
我的第一个版本看起来像这样,我怀疑它可以工作,但代码很丑
string originalFormula;
string newFormula1 = originalFormula.Replace("=", "=test");
string newFormula2 = newFormula1.Replace("+", "+test");
string newFormula3 = newFormula2 .Replace("-", "-test");
string newFormula4 = newFormula3 .Replace("*", "*test");
string newFormula5 = newFormula4 .Replace("/", "/test");
有没有更短的方法来实现它?
【问题讨论】:
-
如果可行,您应该使用它。你绝对不会发现任何更短、更高效或更具可读性的东西。
-
因为
Replace返回更新后的字符串,您可以链接每个Replace调用:string newFormula = originalFormula.Replace("=", "=test").Replace("+", "+test").Replace("-", "-test").Replace("*", "*test").Replace("/", "/test");- 我不知道它是否使它更具可读性。 -
另外,这个问题展示了如何使用可能有用的搜索替换对字典 - stackoverflow.com/questions/1231768/…
-
@TimSchmelter 我会说它更具可读性(哈哈,半讽刺)...正则表达式是
"[=+*/-]",替换是"$$test"...见regexstorm.net/tester?p=%5b%3d%2b*% 2f-%5d&i=%3dABC%2bDEF&r=%24%24test . -
我投票结束这个问题,因为 OP 试图改进工作代码(甚至不清楚他为什么需要改进它)