[英]Replace the first occurrence in a string
I have this string :我有这个字符串:
Hello my name is Marco
and I'd like to replace the first space (between Hello
and my
) with <br />
.我想用<br />
替换第一个空格(在Hello
和my
之间)。 Only the first.只有第一个。
What's the best way to do it on C#/.NET 3.5?在 C#/.NET 3.5 上执行此操作的最佳方法是什么?
public static class MyExtensions
{
public static string ReplaceFirstOccurrance(this string original, string oldValue, string newValue)
{
if (String.IsNullOrEmpty(original))
return String.Empty;
if (String.IsNullOrEmpty(oldValue))
return original;
if (String.IsNullOrEmpty(newValue))
newValue = String.Empty;
int loc = original.IndexOf(oldValue);
return original.Remove(loc, oldValue.Length).Insert(loc, newValue);
}
}
and use it like:并使用它:
string str="Hello my name is Marco";
str.ReplaceFirstOccurrance("Hello", "<br/>");
str.ReplaceFirstOccurrance("my", "<br/>");
No need to add substrings, following will find the first space instance only.不需要添加子串,后面只会找到第一个空格实例。 From MSDN :从MSDN :
Reports the zero-based index of the first occurrence of the specified string in this instance.报告此实例中第一次出现指定字符串的从零开始的索引。
string x = "Hello my name is Marco";
int index = x.IndexOf(" ");
if (index >= 0)
{
x=x.Remove(index,1);
x = x.Insert(index, @"<br />");
}
Edit: If you are not sure if space will occur, some validations must come into place.编辑:如果您不确定是否会出现空间,则必须进行一些验证。 I have edit the answer accordingly.我已经相应地编辑了答案。
string tmp = "Hello my name is Marco";
int index = tmp.IndexOf(" ");
tmp = tmp.Substring(0, index) + "<br />" + tmp.Substring(index + 1);
Here you go, this would work:给你,这行得通:
var s = "Hello my name is Marco";
var firstSpace = s.IndexOf(" ");
var replaced = s.Substring(0,firstSpace) + "<br/>" + s.Substring(firstSpace+1);
You could make this into an extension method:你可以把它变成一个扩展方法:
public static string ReplaceFirst(this string input, string find, string replace){
var first= s.IndexOf(find);
return s.Substring(0,first) + replace + s.Substring(first+find.Length);
}
And then the usage would be然后用法是
var s = "Hello my name is Marco";
var replaced = s.ReplaceFirst(" ","<br/>");
string[] str = "Hello my name is Marco".Split(' ');
string newstr = str[0] + "<br /> " + string.Join(" ", str.Skip(1).ToArray());
只需使用
Replace("Hello my name is Marco", " ", "<br />", 1, 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.