[英].NET String.Replace
I am so annoyed. 我好恼火。 Typically I like replace acting as it does in C# but is there a C++ styled replace where it only replaces one letter at a time or the X amount I specify?
通常我喜欢像C#中那样替换动作,但是有一个C ++样式的替换,它一次只替换一个字母或我指定的X量吗?
No there is not a Replace method in the BCL which will replace only a single instance of the character. 没有在BCL中没有替换方法,它只会替换该字符的单个实例。 The two main Replace methods will replace all occurances.
两种主要的替换方法将取代所有出现。 However, it's not terribly difficult to write a version that does a single character replacement.
但是,编写一个替换单个字符的版本并不是非常困难。
public static string ReplaceSingle(this string source, char toReplace, char newChar) {
var index = source.IndexOf(toReplace);
if ( index < 0 ) {
return source;
}
var builder = new StringBuilder();
for( var i = 0; i < source.Length; i++ ) {
if ( i == index ) {
builder.Append(newChar);
} else {
builder.Append(source[i]);
}
}
return builder.ToString();
}
如果您只想替换一个出现,只需使用IndexOf和SubString。
public string ReplaceString(string source,int index,string newString)
{
char[] sourceArray=source.ToCharArray();
char[] newArray=newString.ToCharArray();
for(int i=index;i<index+newString.Length ;i++)
sourceArray[i]=newArray[i];
return new string(sourceArray);
}
If you're interested in doing a character-for-character replacement (especially if you only want to do a particular number of operations), you'd probably do well to convert your string to a char[]
and do your manipulations there by index, then convert it back to a string. 如果你有兴趣进行角色替换(特别是如果你只想进行特定数量的操作),你可能最好将你的字符串转换为
char[]
并在那里进行操作index,然后将其转换回字符串。 You'll save yourself some needless string creation, but this will only work if your replacements are the same length as what you're replacing. 你可以节省一些不必要的字符串创建,但这只有在你的替换长度与你要替换的长度相同时才有效。
您可以编写一个扩展方法来替换第一个匹配项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.