Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

c# - Property or indexer 'string.this[int]' cannot be assigned to -- it's read only

I didn't get the problem - I was trying to do a simple action:

for(i = x.Length-1, j = 0 ; i >= 0 ; i--, j++)
{
    backx[j] = x[i];
}

Both are declared:

String x;
String backx;

What is the problem ? It says the error in the title... If there is a problem - is there another way to do that? The result (As the name 'backx' hints) is that backx will contain the string X backwards. P.S. x is not empty - it contains a substring from another string.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Strings are immutable: you can retrieve the character at a certain position, but you cannot change the character to a new one directly.

Instead you'll have to build a new string with the change. There are several ways to do this, but StringBuilder does the job in a similar fashion to what you already have:

StringBuilder sb = new StringBuilder(backx);
sb[j] = x[i];
backx = sb.ToString();

EDIT: If you take a look at the string public facing API, you'll see this indexer:

public char this[int index] { get; }

This shows that you can "get" a value, but because no "set" is available, you cannot assign values to that indexer.

EDITx2: If you're looking for a way to reverse a string, there are a few different ways, but here's one example with an explanation as to how it works: http://www.dotnetperls.com/reverse-string


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...