繁体   English   中英

C# 在一个字符串中一次做许多替换

[英]C# do many replacements at once in a String

我有一本替换字典

var substitutions = new Dictionary<string, string>()
{
    { "one", "two" },
    { "two", "three" },
};

我想把字符串“一二三四”变成“二三三四”。

运行任何类型的迭代替换链,例如

var phrase = "one two three four";
substitutions.Aggregate(phrase, (current, substitution) => current.Replace(substitution.Key, substitution.Value)));

或者

var sb = new StringBuilder(phrase);
foreach (var entry in substitutions)
{
    sb.Replace(entry.Key, entry.Value);
}
sb.ToString();

产生“三三三四”,因为第二个替换“二”→“三”能够从之前的 output 中看到“一”→“二”output。

我怎样才能只替换“原始”词?

将字符串拆分为单独的术语,现在您只需迭代一次并替换:

var phrase = "one two three four";
var terms = phrase.Split();

for(int i = 0; i < terms.Length; i++)
{
  if(substitutions.ContainsKey(terms[i]))
  {
    terms[i] = substitutions[terms[i]];
  }
}

phrase = string.Join(" ", terms);

您可以按如下方式使用正则表达式:

var substitutions = new Dictionary<string, string>()
{
    { "one", "two" },
    { "two", "three" },
};

var phrase = "one two three four";

var pattern = string.Join("|", substitutions.Keys.Select(Regex.Escape));

// Pattern is: one|two

var result = Regex.Replace(phrase, pattern, match => substitutions[match.Value]);

工作示例


如果替换必须只匹配完整的单词,您可以更新pattern以包含单词边界\b

substitutions.Keys.Select(x => @$"\b{Regex.Escape(x)}\b")

工作示例

因为它总是被空格分割的单个单词,所以只需分割字符串并循环遍历该集合以重建新结果

var substitutions = new Dictionary<string, string>()
{
    { "one", "two" },
    { "two", "three" },
};
var phrase = "one two three four";

// convert to list of words
var words = phrase.Split(new[] { " " }, StringSplitOptions.None).ToList();

// keep the transformed result
var result = new StringBuilder();

// for each words
foreach (var word in words)
{
    // add a space before since we removed it.
    // will trim later on for the first useless space it creates
    result.Append(" ");

    // to get the dictionary value
    string substitutionWord;

    // if we found the dictionary key
    if (substitutions.TryGetValue(word, out substitutionWord))
    {
        // add substitution word instead
        result.Append(substitutionWord);
    }
    else // not found
    {
        // keep the original word
        result.Append(word);
    }
}

var finalResult = result.ToString().Trim();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM