.NET与string.replace [英] .NET String.Replace
本文介绍了.NET与string.replace的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很恼火。通常情况下,我喜欢替代作用,因为它在C#中,但有一个C ++风格取代它只替换一个字母的时间或我指定x量?
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?
推荐答案
没有没有一个在BCL替换法将取代该字符只有一个实例。两个主要的替代方法将取代所有出现。然而,这并不难写,做一个字符替换版本。
No there is not a Replace method in the BCL which will replace only a single instance of the character. 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();
}
这篇关于.NET与string.replace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文