Change value of ONE letter/number in a String

I have a String variable:

“Hey 9123, i am JoSo 123.Bye”

and im trying to change ONE letter or number in this string:

Letter(e) → “Hey 9123, i em JoSo 123.Bye”
Number(9) → “Hey 9123, i am JoSo 923.Bye”

Hope someone can help me.

Hey @SoJo

you can use the overload of Regex.Replace to specify the maximum number of times to replace…

var regex = new Regex(Regex.Escape("a"));

var newText = regex.Replace("Hey 9123, i am JoSo 123.Bye", "e", 1); 

and same for the second.

var regex = new Regex(Regex.Escape("9"));
var newText = regex.Replace("Hey 9123, i am JoSo 123.Bye", "9", 1); 

There are a number of ways that you could do this, but the fastest might be to use IndexOf to find the index position of the letter you want to replace and then substring out the text before and after what you want to replace.

hope it is useful for you, Let me know :slight_smile:

Regards…!!
Aksh

1 Like

What about String.Replace?

Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.

He wants to replace only one and first occurrence of that character so by “String.Replace” also you can achieve but for that you have to pass the index of that character so have to use Indexof, i have mentioned this way as well.

Regards…!!
Aksh

1 Like