Is there an easy way to change a char in a string

2019-01-19 00:24发布

I want to do this:

string s = "abc";
s[1] = 'x';

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:

"Property or indexer 'string.this[int]' cannot be assigned to -- it is read only"

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]?

Thanks in advance.

标签: c# string char
8条回答
爷、活的狠高调
2楼-- · 2019-01-19 00:54

Strings are immutable which is why there's no setter, you can however use a string builder:

StringBuilder s = new StringBuilder("abc");

s[1] = 'x';
查看更多
Deceive 欺骗
3楼-- · 2019-01-19 01:06

I don't think you can do this in C#, as the string cannot be altered (just destroyed and recreated). Have a look at the StringBuilder class.

查看更多
做自己的国王
4楼-- · 2019-01-19 01:08

(Your example is slightly wrong: s[2] = 'x' should change it to "abx".)

No you can't, since strings are immutable, you have to create a new string:

http://en.wikipedia.org/wiki/Immutable_object

You should use a method that returns a new string with the desired modification.

Hope that helps!

查看更多
贪生不怕死
5楼-- · 2019-01-19 01:08

Why not do this if you're using some Linq

private string ConvertStr(string inStr , int inIndex , char inChar)
{
char[] tmp = inStr.ToCharArray();
tmp.SetValue(inChar , inIndex);
return new string(tmp);
}

That should let you replace whatever char you want with whatever char you want.

查看更多
贼婆χ
6楼-- · 2019-01-19 01:10

What's about this?

string originalString = "abc";

        var index = 1;
        char charToReplace = 'x';

        var newString = string.Format("{0}{1}{2}", originalString.Substring(0, index), charToReplace, originalString.Substring(index + 1));
查看更多
乱世女痞
7楼-- · 2019-01-19 01:10

yes in c# string can not be altered.

but we can try this

string s = "abc";
s = s.Replace('b', 'x');
Console.WriteLine(s);

answer will be "axc". as this will replace the old string with new string.

查看更多
登录 后发表回答