VVS*_*VVS 127
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);
}
Run Code Online (Sandbox Code Playgroud)
例:
string str = "The brown brown fox jumps over the lazy dog";
str = ReplaceFirst(str, "brown", "quick");
Run Code Online (Sandbox Code Playgroud)
编辑:正如@itsmatt 提到的,还有Regex.Replace(String,String,Int32),它可以做同样的事情,但在运行时可能更贵,因为它使用的是一个功能齐全的解析器,我的方法可以找到一个和三个字符串级联.
EDIT2:如果这是一项常见任务,您可能希望将该方法作为扩展方法:
public static class StringExtension
{
public static string ReplaceFirst(this string text, string search, string replace)
{
// ...same as above...
}
}
Run Code Online (Sandbox Code Playgroud)
使用上面的例子,现在可以编写:
str = str.ReplaceFirst("brown", "quick");
Run Code Online (Sandbox Code Playgroud)
Wes*_*ard 62
正如它所说的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"
Run Code Online (Sandbox Code Playgroud)
第三个参数(在本例中设置为1)是要从字符串开头在输入字符串中替换的正则表达式模式的出现次数.
我希望这可以通过静态Regex.Replace重载来完成,但不幸的是,你需要一个Regex实例才能完成它.
Mar*_*ell 15
考虑到"仅限第一",或许:
int index = input.IndexOf("AA");
if (index >= 0) output = input.Substring(0, index) + "XQ" +
input.Substring(index + 2);
Run Code Online (Sandbox Code Playgroud)
?
或者更一般地说:
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);
}
Run Code Online (Sandbox Code Playgroud)
然后:
string output = input.ReplaceFirstInstance("AA", "XQ");
Run Code Online (Sandbox Code Playgroud)
小智 11
using System.Text.RegularExpressions;
RegEx MyRegEx = new RegEx("F");
string result = MyRegex.Replace(InputString, "R", 1);
Run Code Online (Sandbox Code Playgroud)
首先发现F
的InputString
,并取代它R
.
在C#语法中:
int loc = original.IndexOf(oldValue);
if( loc < 0 ) {
return original;
}
return original.Remove(loc, oldValue.Length).Insert(loc, newValue);
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
请享用
假设AA
仅当它位于字符串的开头时才需要替换:
var newString;
if(myString.StartsWith("AA"))
{
newString ="XQ" + myString.Substring(2);
}
Run Code Online (Sandbox Code Playgroud)
如果您需要替换第一次出现的AA
,无论字符串是否以它开头,请使用 Marc 的解决方案。
归档时间: |
|
查看次数: |
63061 次 |
最近记录: |