Replacing a Character in a String

C

C# Learner

What's the "standard" way of replacing a character in a string?
Obviously, I can't say "myString[index] = character;" because strings
are immutable...

So what would be the "standard" way of doing this?

TIA
 
G

gabriel

C# Learner said:
Obviously, I can't say "myString[index] = character;" because strings
are immutable...

OK, if the above is a no-no for you, then use the StringBuilder class.
 
G

Guest

myString = myString.Replace("xyz", "abc")

Tu-Thac

----- C# Learner wrote: ----

What's the "standard" way of replacing a character in a string
Obviously, I can't say "myString[index] = character;" because string
are immutable..

So what would be the "standard" way of doing this

TI
 
G

Gary Morris

Dont know if there is necessarily a "standard" way, but here
is what I would do:

StringBuilder s = new StringBuilder("astringoftext");
s[11] = 'q';
string sNew = s.ToString();

sNew is now "astringofteqt"

and can now be assigned to the original string..
 
M

Mihai N.

What's the "standard" way of replacing a character in a string?
Obviously, I can't say "myString[index] = character;" because strings
are immutable...

So what would be the "standard" way of doing this?

If you want to change one character with another one
use String.Replace

If you want to change one char at a certain index
use String.ToCharArray, do your change, then construct a new string from it
(not the most efficient way)

If it is necessary to modify the actual contents of a string-like object, use
the System.Text.StringBuilder class.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top