我要替换第一次出现一个给定的字符串研究。
我怎样才能做到这一点。NET中?
解决方案 字符串ReplaceFirst(文本字符串,字符串搜索,字符串替换)
{
INT POS = text.IndexOf(搜索);
如果(POS℃,)
{
返回文本;
}
返回text.Substring(0,POS)+替换+ text.Substring(POS + search.Length);
}
例如:
字符串str =褐棕色狐狸跳过懒狗;
海峡= ReplaceFirst(STR,棕色,快);
修改:作为@itsmatt 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");
上一篇:计划找素数素数、计划