有没有一种简单的方法可以在 C# 中更改字符串中的字符?

4

本文介绍了有没有一种简单的方法可以在 C# 中更改字符串中的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我想这样做:

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# 中更改字符串中的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14