4

If I have string and I want to replace last character from that string with star for example.

I tried this

var myString = "ABCDEFGH";
myString.ReplaceCharacter(mystring.Length - 1, 1, "*"); 

public static string ReplaceCharacter(this string str, int start, int length, string replaceWith_expression)
{
    return str.Remove(start, length).Insert(start, replaceWith_expression);
}

I tried to use this extension method but this doesn't work. Why this doesn't work?

adricadar
  • 9,971
  • 5
  • 33
  • 46
user2783193
  • 992
  • 1
  • 12
  • 37
  • possible duplicate of [C# string replace does not work](http://stackoverflow.com/questions/13277667/c-sharp-string-replace-does-not-work) – Eugene Podskal May 27 '15 at 20:12

2 Answers2

8

The method, as it is, replace the character, but you have to catch the result

myString = myString.ReplaceCharacter(myString.Length - 1, 1, "*"); 
adricadar
  • 9,971
  • 5
  • 33
  • 46
2

The problem is that strings are immutable. The methods replace, substring etc do not change the string itself. They create a new string and replace it. So for the above code to be correct it should be

myString = myString.ReplaceCharacter(myString.Length - 1, 1, "*"); 
Manoj Pedvi
  • 169
  • 8
  • 15