如何改变1字符的字符串? [英] How to change 1 char in the string?

查看:154
本文介绍了如何改变1字符的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的下一个code:

string str = "valta is the best place in the World";

和我需要更换的第一个符号,我这样做的:

And i need to replace the first symbol, i do so:

str[0] = 'M';

不过,我收到一个错误。我怎样才能做到这一点?

But I recieve an error. How can I do this?

推荐答案

字符串是不可变的,这意味着你不能改变一个字符。相反,你创建新的字符串。

Strings are immutable, meaning you can't change a character. Instead, you create new strings.

你问有什么方法可以有多种方式。最合适的解决方案将取决于你正在以原始字符串的变化特点而有所不同。你只改变一个字符?你需要插入/删除/添加?

What you are asking can be done several ways. The most appropriate solution will vary depending on the nature of the changes you are making to the original string. Are you changing only one character? Do you need to insert/delete/append?

下面有几个方法可以创建从现有字符串的新字符串,但有一个不同的第一个字符:

Here are a couple ways to create a new string from an existing string, but having a different first character:

str = 'M' + str.Remove(0, 1);

str = 'M' + str.Substring(1);

以上,新的字符串被分配给原来的变量, STR

我想补充一点,从别人的答案展示的StringBuilder 也非常合适。我不会实例化一个的StringBuilder 来改变一个人的性格,但如果需要许多变化的StringBuilder 比一个更好的解决方案我的例子而创建的过程中一个暂新的字符串。 的StringBuilder 提供了一个可变对象,让许多变化和/或追加操作。一旦你完成更改,不可变的字符串是从的StringBuilder 的ToString()方法创建的。您可以继续根据需要使的StringBuilder 对象上的变化,创造更多新的字符串,用的ToString()

I'd like to add that the answers from others demonstrating StringBuilder are also very appropriate. I wouldn't instantiate a StringBuilder to change one character, but if many changes are needed StringBuilder is a better solution than my examples which create a temporary new string in the process. StringBuilder provides a mutable object that allows many changes and/or append operations. Once you are done making changes, an immutable string is created from the StringBuilder with the .ToString() method. You can continue to make changes on the StringBuilder object and create more new strings, as needed, using .ToString().

这篇关于如何改变1字符的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆