Is there an easy way to change a char in a string in C#?(有没有一种简单的方法可以在 C# 中更改字符串中的字符?)
问题描述
我想这样做:
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# 中更改字符串中的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:有没有一种简单的方法可以在 C# 中更改字符串中的字符?


- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 使用 rss + c# 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01