C# 如何更改字符串中的 1 个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8987141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change 1 char in the string?
提问by Vasya
I have this code:
我有这个代码:
string str = "valta is the best place in the World";
I need to replace the first symbol. When I try this:
我需要替换第一个符号。当我尝试这个时:
str[0] = 'M';
I received an error. How can I do this?
我收到一个错误。我怎样才能做到这一点?
采纳答案by Kevin P. Rice
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);
Above, the new string is assigned to the original variable, str.
上面,新字符串被分配给原始变量,str。
I'd like to add that the answers from others demonstrating StringBuilderare also very appropriate. I wouldn't instantiate a StringBuilderto change one character, but if many changes are needed StringBuilderis a better solution than my examples which create a temporary new string in the process. StringBuilderprovides a mutable object that allows many changes and/or append operations. Once you are done making changes, an immutable string is created from the StringBuilderwith the .ToString()method. You can continue to make changes on the StringBuilderobject and create more new strings, as needed, using .ToString().
我想补充一点,其他人演示的答案StringBuilder也非常合适。我不会实例化 aStringBuilder来更改一个字符,但是如果需要进行许多更改,这StringBuilder是比我的示例更好的解决方案,这些示例在此过程中创建了一个临时的新字符串。StringBuilder提供一个可变对象,允许许多更改和/或追加操作。完成更改后,会从StringBuilderwith.ToString()方法创建一个不可变的字符串。您可以继续对StringBuilder对象进行更改,并根据需要使用.ToString().
回答by Chuck Norris
I suggest you to use StringBuilderclass for it and than parse it to string if you need.
我建议你使用StringBuilder类,如果你需要的话,不要将它解析为字符串。
System.Text.StringBuilder strBuilder = new System.Text.StringBuilder("valta is the best place in the World");
strBuilder[0] = 'M';
string str=strBuilder.ToString();
You can't change string's characters in this way, because in C# string isn't dynamic and is immutable and it's chars are readonly. For make sure in it try to use methods of string, for example, if you do str.ToLower()it makes new string and your previous string doesn't change.
您不能以这种方式更改字符串的字符,因为在 C# 中,字符串不是动态的并且是不可变的,并且它的字符是只读的。为了确保在其中尝试使用字符串的方法,例如,如果您这样做str.ToLower()会生成新字符串并且您之前的字符串不会更改。
回答by Jon Hanna
str = "M" + str.Substring(1);
If you'll do several such changes use a StringBuilderor a char[].
如果您要进行多次此类更改,请使用 aStringBuilder或 a char[]。
(The threshold of when StringBuilderbecomes quicker is after about 5 concatenations or substrings, but note that grouped concatenations of a + "b" + c + d + "e" + fare done in a single call and compile-type concatenations of "a" + "b" + "c"don't require a call at all).
(何时StringBuilder变得更快的阈值是在大约 5 个连接或子字符串之后,但请注意, 的分组连接a + "b" + c + d + "e" + f是在单个调用中完成的,而编译类型的连接"a" + "b" + "c"根本不需要调用)。
It may seem that having to do this is horribly inefficient, but the fact that strings can't be changes allows for lots of efficiency gains and other advantages such as mentioned at Why .NET String is immutable?
似乎不得不这样做是非常低效的,但字符串不能更改的事实允许大量的效率提升和其他优势,例如为什么 .NET 字符串是不可变的?
回答by Jeb
Strings are immutable. You can use the string builder class to help!:
字符串是不可变的。您可以使用字符串生成器类来提供帮助!:
string str = "valta is the best place in the World";
StringBuilder strB = new StringBuilder(str);
strB[0] = 'M';
回答by Paulo Mendon?a
I made a Method to do this
我做了一个方法来做到这一点
string test = "Paul";
test = ReplaceAtIndex(0, 'M', test);
(...)
static string ReplaceAtIndex(int i, char value, string word)
{
char[] letters = word.ToCharArray();
letters[i] = value;
return string.Join("", letters);
}
回答by natenho
Merged Chuck Norris's answer w/ Paulo Mendon?a's using extensions methods:
使用扩展方法将 Chuck Norris 的答案与 Paulo Mendon?a 合并:
/// <summary>
/// Replace a string char at index with another char
/// </summary>
/// <param name="text">string to be replaced</param>
/// <param name="index">position of the char to be replaced</param>
/// <param name="c">replacement char</param>
public static string ReplaceAtIndex(this string text, int index, char c)
{
var stringBuilder = new StringBuilder(text);
stringBuilder[index] = c;
return stringBuilder.ToString();
}
回答by badweasel
While it does not answer the OP's question precisely, depending on what you're doing it might be a good solution. Below is going to solve my problem.
虽然它没有准确回答 OP 的问题,但取决于您在做什么,它可能是一个很好的解决方案。下面将解决我的问题。
Let's say that you have to do a lot of individual manipulation of various characters in a string. Instead of using a string the whole time use a char[]array while you're doing the manipulation. Because you can do this:
假设您必须对字符串中的各种字符进行大量单独操作。char[]在进行操作时,不要一直使用字符串,而是使用数组。因为你可以这样做:
char[] array = "valta is the best place in the World".ToCharArray();
Then manipulate to your hearts content as much as you need...
然后根据您的需要尽可能多地操纵您的内心......
array[0] = "M";
Then convert it to a string once you're done and need to use it as a string:
然后在完成后将其转换为字符串并需要将其用作字符串:
string str = new string(array);

