views:

1293

answers:

5

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?

+2  A: 

Just use IndexOf and SubString if you only want to replace one occurance.

Joel Coehoorn
+4  A: 

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();
}
JaredPar
A: 

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. 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.

Adam Robinson
A: 

You could write an extension method to replace just the first occurrence.

Brian Ensink
A: 
Abdullah Hazeb
1) There was already an answer and i have accepted it. 2) You didnt use the 1010 code button which make this unreadable.
acidzombie24