String Manipulation

  • Thread starter Thread starter INeedADip
  • Start date Start date
I

INeedADip

How can I change a particular char at a given index....
I want to do something like:

strText[2] = 'b';

But apparently the "strText[2]" is readonly?
Is there another way to get access to a particular character?
 
You cannot. Strings are immutable, even for replacing a character that
already exists.
 
INeedADip said:
How can I change a particular char at a given index....
I want to do something like:

strText[2] = 'b';

But apparently the "strText[2]" is readonly?
Is there another way to get access to a particular character?

Strings are immutable in .NET. If you need a different sequence of
characters, you need a different string object.

The best way of doing this depends on exactly what you need to do - do
you genuinely only need to change a single character, or is that just
an example?
 
INeedADip said:
How can I change a particular char at a given index....
I want to do something like:

strText[2] = 'b';

But apparently the "strText[2]" is readonly?
Is there another way to get access to a particular character?

Use a StringBuilder...

StringBuilder textBuilder = new StringBuilder(256);

textBuilder.Append(strText);
textBuilder.Remove(2, 1);
textBuilder.Insert('b', 2);
strText = textBuilder.ToString();

I hope this helps.

carl
 
Hi
You can use StringBuilder instead of string. And Change Or access
purticular character.

e.g
StringBuilder sb = new StringBuilder("My Test String");
sb[5] = 'x';
String str = sb.ToString();
 
Back
Top