Adding characters to a string : Error 'string.this[int]' cannot be assigned to -- it is read only

  • Thread starter Thread starter J. Oliver
  • Start date Start date
J

J. Oliver

I am attempting to copy a portion of a string into another string. Say
I have "abcdef" in string 'a' and want to copy only "bcd" into a new
string 'b'. The following function came to mind:

public string GetText(string a, int start, int end)

{
int i;
string b;

for (i=0;i<(end-start);i++)
{
b=(a[start+i]);
}

return b;
}


At compile time, I am getting the error: "Property or indexer
'string.this[int]' cannot be assigned to -- it is read only"

Which makes sense, since I am attempting to increase the sisce of a
fixed string. Is there an easier way to do this?

- j. oliver
 
Hi

Use StringBuilder instead of String.
Then you can use StringBuilder.Append();

HTH
Ravikanth[MVP]
 
I used a PERL primer for my knowledge of RegExp.
Many to be found as ebooks online, for free. Maybe useful ?

Best
Stu
 
Hi!

Well, in your case you could simply use the string.Substring(int index, int
length) to get the string you need.

string b = a.Substring(start, end-start);

Fairly simple.

If you on the other hand want to add characters and so on you could alway
use the StringBuilder (System.Text)

System.Text.StringBuilder sb = new StringBuilder(string.Empty); //A new
totally empty stringbuilder

for (int i = start; i < end; i++)
{
sb.Append(str)
}

return sb.ToString(); //returns the string you wanted

I hope this helps!

//Mikael

Stu Banter said:
I used a PERL primer for my knowledge of RegExp.
Many to be found as ebooks online, for free. Maybe useful ?

Best
Stu

J. Oliver said:
I am attempting to copy a portion of a string into another string. Say
I have "abcdef" in string 'a' and want to copy only "bcd" into a new
string 'b'. The following function came to mind:

public string GetText(string a, int start, int end)

{
int i;
string b;

for (i=0;i<(end-start);i++)
{
b=(a[start+i]);
}

return b;
}


At compile time, I am getting the error: "Property or indexer
'string.this[int]' cannot be assigned to -- it is read only"

Which makes sense, since I am attempting to increase the sisce of a
fixed string. Is there an easier way to do this?

- j. oliver

 
Back
Top