【问题标题】:C# String Replace not removing String from End [duplicate]C#字符串替换不从结尾删除字符串[重复]
【发布时间】:2024-05-19 23:10:01
【问题描述】:

我从事自然语言处理,我正在尝试删除字符串的 最后一部分,但它会从 inside 字符串中删除字符串, 我的代码。

public string RemoveSuffix(string word)
{
  if (word.EndsWith("ی")
  { 
    word = word.Replace("ی","");
  }

  return word;
}

【问题讨论】:

  • 给定的输入是什么,你的意思是它不起作用
  • 字符串替换功能替换所有出现的子字符串,你应该使用字符串的删除方法
  • word=word.Replace("ی",""); 将替换所有出现的位置,而不仅仅是后缀。
  • Replace 完全按照它所说的去做——它会替换这个字符串,无论它在哪里找到。为什么它应该只替换 last 出现?
  • @ManfredRadlwimmer OP 说 Replace 从任何位置删除字符,而不仅仅是结尾。正如它应该的那样

标签: c# string


【解决方案1】:

您可能正在寻找TrimEnd

  // static: you have no need in "this"
  public static string RemoveSuffix(string word) {
    return word == null // <- do not forget to validate public method's argument(s)
      ? null            // or throw ArgumentNullException      
      : word.TrimEnd('ی'); 
  }

【讨论】:

  • 也可以写成:public string RemoveSuffix(string word) =&gt; word?.TrimEnd('ی') ?? null;
  • @GiulioCaccin ?? null 有什么意义?你想写?? ""吗?
  • @PanagiotisKanavos 只是为了保持原作者写的语义和 cmets ^_^ 最好用空字符串,我会更新。
  • @GiulioCaccin 然后我再说一遍,?? null 有什么意义?再次阅读您输入的内容。 ?? 仅在左侧值为 null 时才有效。然后它将返回... null。还不如完全删除它
  • 本着俏皮话的精神,抛出异常的表达式体函数可以是RemoveSuffix(string word) =&gt; word?.TrimEnd('ی') ?? throw new ArgumentNullException(nameof(word))
【解决方案2】:

你应该试试

public string RemoveSuffix(string word,string lstPart)
{
 return  word=word.TrimEnd(lstPart);

}

您可以使用变量/列表项更改硬代码字

【讨论】:

  • String 有许多可以提供帮助的方法,包括修剪方法。没必要写这一切。不是我的反对意见,但应该删除这个答案
  • @Edward Islam 感谢这位工作主管,现在我可以为所有后期修复调用此方法,
  • @PanagiotisKanavos 方法名称“RemoveSuffix”对 NLP 研究人员有意义。