【问题标题】:How to replace text in a sentence but avoid certain words/letters?如何替换句子中的文本但避免某些单词/字母?
【发布时间】:2014-10-18 16:33:22
【问题描述】:

所以我有一个人的全名:

string fullName = "Bill Richardson";

假设,我有这句话:

string sentence = "Richardson had a bike and he loved it";

但是这句话只包含人的姓氏,因此我将其替换为:

string modifiedSentence = null;
string[] senSplit = sentence.Split(' ');

foreach(string word in senSplit)
{
   if(fullName.Contains(word))
   {
      modifiedSentence = sentence.Replace(word,fullName);
   }
}

现在我希望修改后的句子是:

Bill Richardson 有一辆自行车,他很喜欢

但显然(我发现了问题),如果 fullName 甚至包含单词“a”,它会被全名替换,因此最终会变成这样:

比尔理查森有比尔理查森的自行车,他很喜欢

那是一场灾难,不是吗? :) 如果可能的话,我该如何以另一种方式做到这一点?谢谢

【问题讨论】:

    标签: c# regex string loops replace


    【解决方案1】:

    你可以这样做

    modifiedSentence = new Regex(string.Join("|", fullName
        .Split(' '))).Replace(sentence, fullName, 1);
    Console.WriteLine(modifiedSentence);
    

    【讨论】:

    • 好的,我试试这个,你能解释一下这个和我的代码之间的区别吗?我也需要理解它:)
    • @ProgrammingFreak 它创建了一个很像or 的正则表达式。因此,它将查找 Bill 或其他单词并将其替换为 fullname
    • @ProgrammingFreak 查看我的新代码...旧代码有语法错误
    • @ProgrammingFreak 很高兴能帮上忙 :)
    【解决方案2】:

    如果您不知道姓氏是全名中的第一个还是第二个,则必须对两者进行迭代,而不是检查它是否包含单词,而是测试两个单词之间的等价性。 请注意,如果 fullName 已经包含在原始句子中,这将不起作用。

    var nameParts=fullName.Split(' ');
    string modifiedSentence = null;
    string[] senSplit = sentence.Split(' ');
    foreach(string part in nameParts)
    {
       foreach(string word in senSplit)
       {
          if(nameParts.Equals(word))
          {
             modifiedSentence = sentence.Replace(word,fullName);
          }
       }
    }
    

    虽然这可以通过更紧凑的内联方式完成,但我认为这会更容易理解并且更类似于您的原始代码。

    【讨论】:

      猜你喜欢
      • 2018-02-14
      • 2021-08-26
      • 1970-01-01
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-30
      • 2021-12-10
      相关资源
      最近更新 更多