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# 中更改字符串中的字符?
基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
