470,636 Members | 1,356 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,636 developers. It's quick & easy.

Replacing a Character in a String

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
Nov 15 '05 #1
4 22525
C# Learner wrote:
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.

--
gabriel
Nov 15 '05 #2
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

Nov 15 '05 #3
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..

"C# Learner" <cs****@learner.here> wrote in message
news:f6********************************@4ax.com...
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

Nov 15 '05 #4
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.
--
Mihai
-------------------------
Replace _year_ with _ to get the real email
Nov 15 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

7 posts views Thread by Justin | last post: by
5 posts views Thread by Karthik | last post: by
25 posts views Thread by lovecreatesbeauty | last post: by
8 posts views Thread by Brand Bogard | last post: by
reply views Thread by Tor Inge Rislaa | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.