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

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

问题描述

我要替换第一次出现一个给定的字符串研究。

我怎样才能做到这一点。NET中?

解决方案

 字符串ReplaceFirst(文本字符串,字符串搜索,字符串替换)
{
  INT POS = text.IndexOf(搜索);
  如果(POS℃,)
  {
    返回文本;
  }
  返回text.Substring(0,POS)+替换+ text.Substring(POS + search.Length);
}
 

例如:

 字符串str =褐棕色狐狸跳过懒狗;

海峡= ReplaceFirst(STR,棕色,快);
 

修改:作为@itsmatt <一个href="http://stackoverflow.com/questions/141045/how-do-i-replace-a-string-in-net#141062">mentioned,另外还有Regex.Replace(字符串,字符串,Int32)在,它可以这样做,但很可能是在运行时更加昂贵,因为它是利用一个功能齐全的解析器在我的方法做一件找到和三个字符串连接。

EDIT2 :如果这是一个共同任务,你可能想使该方法的扩展方法:

 公共静态类StringExtension
{
  公共静态字符串ReplaceFirst(此字符串文本,字符串搜索,字符串替换)
  {
     // ...同上...
  }
}
 

使用上面的例子,现在有可能这样写:

 海峡= str.ReplaceFirst(棕色,快);
 

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

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

Example:

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

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

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: 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天全站免登陆