【问题标题】:Add String into existing String whenever specific characters found每当找到特定字符时,将字符串添加到现有字符串中
【发布时间】: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 试图改进工作代码(甚至不清楚他为什么需要改进它)

标签: c# .net string


【解决方案1】:

如果您希望代码更优雅,请使用正则表达式。

using System.Text.RegularExpressions;

string originalFormula = ...;
var replacedString = Regex.Replace(myString, "[-+*/=]", "$&test");

为了更好地理解: [-+*/=] 将要检查字符串的字符分组。 $&test 将找到的字符替换为匹配的字符 ($&) 并添加 test

【讨论】:

    【解决方案2】:

    如果您的问题是您的代码看起来很难看,也许您可​​以重写它以使用列表而不是...

    List<char> characters = new List<char> { '+', '-', '*', '/' };
    
    foreach (var c in characters)
    {
        string newValue = String.Format("{0}{1}", c, somethingElse);
        if (originalForumla.Contains(c);
        {
            newForumla = originalFormula.Replace(c, newValue);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-27
      • 2023-04-10
      • 2021-01-08
      • 1970-01-01
      相关资源
      最近更新 更多