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# 中更改字符串中的字符?


基础教程推荐
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- c# Math.Sqrt 实现 2022-01-01