我怎么设置索引字符在C#中的字符串? [英] how do I set a character at an index in a string in c#?
本文介绍了我怎么设置索引字符在C#中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
someString[someRandomIdx] = 'g';
这会给我一个错误,
我该如何实现上述?
编辑:
是的,它的类型为字符串
yes it is of type 'string'
推荐答案
如果它的类型为字符串
那么你不能这样做,因为字符串是不可变的 - 他们不能一旦它们被设置来改变。
If it is of type string
then you can't do that because strings are immutable - they cannot be changed once they are set.
要实现你的愿望,你可以使用的StringBuilder
To achieve what you desire, you can use a StringBuilder
StringBuilder someString = new StringBuilder("someString");
someString[4] = 'g';
更新
为什么要用字符串
,而不是的StringBuilder
?有许多原因。这里有一些我能想到的:
Why use a string
, instead of a StringBuilder
? For lots of reasons. Here are some I can think of:
- 访问字符串的值更快。
- 字符串,可以拘留(这并不总是发生),因此,如果您创建一个字符串的值相同则没有额外的内存被使用。
- 字符串是不变的,所以他们基于散列的集合更好的工作和他们固有的线程安全的。
这篇关于我怎么设置索引字符在C#中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文