C# 替换字符串中第一次出现的模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8809354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:32:23  来源:igfitidea点击:

Replace first occurrence of pattern in a string

c#regex

提问by Tono Nam

Possible Duplicate:
How do I replace the first instanceof a string in .NET?

可能的重复:
如何替换.NET 中字符串的第一个实例

Let's say I have the string:

假设我有字符串:

string s = "Hello world.";

how can I replace the first oin the word Hellofor let's say Foo?

我怎样才能替换o单词中的第一个Hello让我们说Foo

In other words I want to end up with:

换句话说,我想结束:

"HellFoo world."

I know how to replace all the o's but I want to replace just the first one

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

采纳答案by Reddog

I think you can use the overload of Regex.Replaceto specify the maximum number of times to replace...

我认为您可以使用Regex.Replace的重载来指定替换的最大次数...

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

回答by Mitchel Sellers

There are a number of ways that you could do this, but the fastest might be to use IndexOf to find the index position of the letter you want to replace and then substring out the text before and after what you want to replace.

有多种方法可以执行此操作,但最快的方法可能是使用 IndexOf 查找要替换的字母的索引位置,然后在要替换的内容前后对文本进行子字符串化。

回答by MethodMan

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);
}

here is an Extension Method that could also work as well per VoidKingrequest

这是一个扩展方法,它也可以根据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);
    }
}