如何在 .NET 中替换字符串的*第一个实例*? [英] How do I replace the *first instance* of a string in .NET?

查看:34
本文介绍了如何在 .NET 中替换字符串的*第一个实例*?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想替换给定字符串中的第一次出现.

I want to replace the first occurrence in a given string.

如何在 .NET 中完成此操作?

How can I accomplish this in .NET?

推荐答案

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

示例:

string str = "The brown brown fox jumps over the lazy dog";

str = ReplaceFirst(str, "brown", "quick");

编辑:作为@itsmatt 提到,还有 Regex.Replace(String, String, Int32),它可以做同样的事情,但在运行时可能更昂贵,因为它使用了一个全功能的解析器,我的方法在其中执行一个查找和三个字符串串联.

EDIT: As @itsmatt mentioned, there's also Regex.Replace(String, String, Int32), which can do the same, but is probably more expensive at runtime, since it's utilizing a full featured parser where my method does one find and three string concatenations.

EDIT2:如果这是一项常见任务,您可能希望将该方法设为扩展方法:

EDIT2: If this is a common task, you might want to make the method an extension method:

public static class StringExtension
{
  public static string ReplaceFirst(this string text, string search, string replace)
  {
     // ...same as above...
  }
}

使用上面的例子,现在可以写:

Using the above example it's now possible to write:

str = str.ReplaceFirst("brown", "quick");

这篇关于如何在 .NET 中替换字符串的*第一个实例*?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆