Is there an easy way to change a char in a string

2019-01-19 00:24发布

I want to do this:

string s = "abc";
s[1] = 'x';

and s will become "axc". However, it seems that string[i] only has a getter and has no setter. The compiler gives me the following error:

"Property or indexer 'string.this[int]' cannot be assigned to -- it is read only"

I guess I could make a loop and change the char i want. but i was just wondering if there is an easy way to do it? And why there isn't a setter for string[i]?

Thanks in advance.

标签: c# string char
8条回答
霸刀☆藐视天下
2楼-- · 2019-01-19 01:15

Remember, in managed and safe .Net, strings are immutable, so even if you could do the above, you'd really be creating a new copy of the string with the replacement.

If you are only replacing one character, a simple loop is probably your best bet.

However, if you are going to make multiple replacements, consider using a StringBuilder:

  string s = "abc";
  var stringBuilder = new StringBuilder(s);
  stringBuilder[1] = 'x';
  s = stringBuilder.ToString();
查看更多
该账号已被封号
3楼-- · 2019-01-19 01:19

Strings are immutable, so you have to make a char[] array, change it, then make it back into a string:

string s = "foo";
char[] arr = s.ToCharArray();
arr[1] = 'x';
s = new string(arr);
查看更多
登录 后发表回答