【问题标题】:Replace first occurrence of pattern in a string [duplicate]替换字符串中第一次出现的模式[重复]
【发布时间】:2012-02-07 05:21:53
【问题描述】:

可能重复:
How do I replace the first instance of a string in .NET?

假设我有字符串:

string s = "Hello world.";

我怎样才能将单词Hello 中的第一个o 替换为Foo

换句话说,我想结束:

"HellFoo world."

我知道如何替换所有的 o,但我只想替换第一个

【问题讨论】:

  • 投票重新打开这个老问题,它明确地涉及模式正则表达式。虽然在这种情况下它被简化为文字字符串,但它在技术上与实际询问不同。不幸的是,副本也被标记为“正则表达式”,尽管它在任何地方都没有包含“模式”。

标签: c# regex


【解决方案1】:

我觉得可以用Regex.Replace的重载来指定最大替换次数……

var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);

【讨论】:

  • 替换的好选择
【解决方案2】:
public string ReplaceFirst(string text, string search, string replace)
{
  int pos = text.IndexOf(search);
  if (pos < 0)
  {
    return text;
  }
  return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}

这是一个扩展方法,也可以根据VoidKing 请求工作

public static class StringExtensionMethods
{
    public static string ReplaceFirst(this string text, string search, string replace)
    {
      int pos = text.IndexOf(search);
      if (pos < 0)
      {
        return text;
      }
      return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
    }
}

【讨论】:

  • 比正则表达式恕我直言要好得多,这就是正则表达式在跳过开销后最终会做的事情。在很长的字符串中,最后的结果很远,正则表达式 impl 可能会更好,因为它支持流式传输 char 数组,但对于小字符串,这似乎更有效......
【解决方案3】:

有很多方法可以做到这一点,但最快的可能是使用 IndexOf 找到要替换的字母的索引位置,然后将要替换的文本前后的文本子串出。

if (s.Contains("o"))
{
    s = s.Remove(s.IndexOf('o')) + "Foo" + s.Substring(s.IndexOf('o') + 1);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 2018-10-30
    • 2011-06-05
    • 2011-08-25
    • 2016-11-02
    相关资源
    最近更新 更多