本文介绍了有没有一种简单的方法可以在C#中更改字符串中的char?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想这样做:
string s = "abc";
s[1] = 'x';
和s将成为 axc。但是,string [i]似乎只有一个吸气剂而没有二传手。编译器给我以下错误:
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:
我想我可以做一个循环并更改想要的字符。但我只是想知道是否有一种简单的方法?以及为什么没有针对字符串[i]的设置器?
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#中更改字符串中的char?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!