问题描述
我想这样做:
string s = "abc";
s[1] = 'x';
和 s 将变成axc".但是,似乎 string[i] 只有一个 getter 而没有 setter.编译器给了我以下错误:
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:
"属性或索引器'string.this[int]' 无法赋值to -- 它是只读的"
"Property or indexer 'string.this[int]' cannot be assigned to -- it is read only"
我想我可以创建一个循环并更改我想要的字符.但我只是想知道是否有一种简单的方法可以做到这一点?为什么没有 string[i] 的 setter?
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]?
提前致谢.
推荐答案
字符串是不可变的,所以你必须创建一个 char[]
数组,对其进行更改,然后将其重新变为字符串:
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);
这篇关于有没有一种简单的方法可以在 C# 中更改字符串中的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!