2
string input = "testeeeeeee";
char[] temp = input.ToCharArray();
var test = Regex.Replace(input.Replace(temp[1].ToString(), "@").Trim(), @"\s+", " ");
Console.WriteLine(test);

This is the code I have now, I want my second char on a string to be replaced with "@" , now is the problem that every e will be replaced in @ , how to fix it that only the second char will be replaced and nothing more?

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
  • Strings are immutable. You may use either StringBuilder, a character array or just concatenate two substrings. Find a very similar answer here https://stackoverflow.com/a/5990142/6521550 – Anup Kumar Gupta Sep 28 '17 at 12:44

2 Answers2

10

One way is to just assign a new value to the second char:

var input = "testeeeeeee".ToCharArray();
input[1] = '@';

var result = new string(input);

You'd want to do something like input[1] = @ on the original string and not the char[] but as strings are immutable you cannot change it and the indexer is read-only.


Another way (which I think is less advisable):

var input = "testeeeeeee";
var result =  input[0] + "@" + string.Concat(input.Skip(2));

For the second way it is cleaner to use SubString to get the string from the second index until the end

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
0

You can use the Substring function

string input = "testeeeeeee";
string new_input = input.Substring(0, 1) + "@" + input.Substring(2, input.Length)
gogaz
  • 2,323
  • 2
  • 23
  • 31