C# 如何在 .NET 中替换字符串的*第一个实例*?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/141045/
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
How do I replace the *first instance* of a string in .NET?
提问by
I want to replace the first occurrence in a given string.
我想替换给定字符串中的第一次出现。
How can I accomplish this in .NET?
我怎样才能在 .NET 中做到这一点?
回答by itsmatt
Take a look at Regex.Replace.
回答by VVS
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.
编辑:正如@itsmatt提到的,还有 Regex.Replace(String, String, Int32),它可以做同样的事情,但在运行时可能更昂贵,因为它使用了一个全功能的解析器,我的方法在其中执行一个查找和三个字符串串联。
EDIT2: If this is a common task, you might want to make the method an extension method:
EDIT2:如果这是一项常见任务,您可能希望将该方法设为扩展方法:
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");
回答by Bill the Lizard
In C# syntax:
在 C# 语法中:
int loc = original.IndexOf(oldValue);
if( loc < 0 ) {
return original;
}
return original.Remove(loc, oldValue.Length).Insert(loc, newValue);
回答by mortenbpost
C# extension method that will do this:
将执行此操作的 C# 扩展方法:
public static class StringExt
{
public static string ReplaceFirstOccurrence(this string s, string oldValue, string newValue)
{
int i = s.IndexOf(oldValue);
return s.Remove(i, oldValue.Length).Insert(i, newValue);
}
}
Enjoy
享受
回答by Anthony Potts
And because there is also VB.NET to consider, I would like to offer up:
因为还有 VB.NET 需要考虑,我想提供:
Private Function ReplaceFirst(ByVal text As String, ByVal search As String, ByVal replace As String) As String
Dim pos As Integer = text.IndexOf(search)
If pos >= 0 Then
Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)
End If
Return text
End Function
回答by Wes Haggard
As itsmattsaid Regex.Replaceis a good choice for this however to make his answer more complete I will fill it in with a code sample:
正如itsmatt所说,Regex.Replace是一个不错的选择,但是为了让他的答案更完整,我将用代码示例填充它:
using System.Text.RegularExpressions;
...
Regex regex = new Regex("foo");
string result = regex.Replace("foo1 foo2 foo3 foo4", "bar", 1);
// result = "bar1 foo2 foo3 foo4"
The third parameter, set to 1 in this case, is the number of occurrences of the regex pattern that you want to replace in the input string from the beginning of the string.
在本例中设置为 1 的第三个参数是您要在输入字符串中从字符串开头替换的正则表达式模式的出现次数。
I was hoping this could be done with a static Regex.Replaceoverload but unfortunately it appears you need a Regex instance to accomplish it.
我希望这可以通过静态Regex.Replace重载来完成,但不幸的是,您似乎需要一个 Regex 实例来完成它。
回答by Deenesh
using System.Text.RegularExpressions;
RegEx MyRegEx = new RegEx("F");
string result = MyRegex.Replace(InputString, "R", 1);
will find first F
in InputString
and replace it with R
.
首先发现F
的InputString
,并取代它R
。
回答by Marc Gravell
Taking the "first only" into account, perhaps:
考虑到“第一个”,也许:
int index = input.IndexOf("AA");
if (index >= 0) output = input.Substring(0, index) + "XQ" +
input.Substring(index + 2);
?
?
Or more generally:
或更一般地说:
public static string ReplaceFirstInstance(this string source,
string find, string replace)
{
int index = source.IndexOf(find);
return index < 0 ? source : source.Substring(0, index) + replace +
source.Substring(index + find.Length);
}
Then:
然后:
string output = input.ReplaceFirstInstance("AA", "XQ");
回答by Oded
Assumes that AA
only needs to be replaced if it is at the very start of the string:
假设AA
仅当它位于字符串的最开始时才需要替换:
var newString;
if(myString.StartsWith("AA"))
{
newString ="XQ" + myString.Substring(2);
}
If you need to replace the first occurrence of AA
, whether the string starts with it or not, go with the solution from Marc.
如果您需要替换第一次出现的AA
,无论字符串是否以它开头,请使用 Marc 的解决方案。
回答by Oded
string abc = "AAAAX1";
if(abc.IndexOf("AA") == 0)
{
abc.Remove(0, 2);
abc = "XQ" + abc;
}