olive
olive

Reputation: 3143

How can I replace a character in a string with something else?

I'm making a program. Now to write the data in the file I need to replace the spaces in the string obtained with lets say a # symbol.

Is there any command in C# that lets me do this without looping through the whole string?

Upvotes: 0

Views: 3234

Answers (4)

llMll
llMll

Reputation: 505

Did you try using the Replace method of the string object. This will do the trick:

string newString = oldString.Replace(" ", "#");

Upvotes: 0

Sambo
Sambo

Reputation: 1472

Be sure to retrieve the returned string from the Replace() method as it won't change the original string...it generates a new one.

Upvotes: 0

Fun Mun Pieng
Fun Mun Pieng

Reputation: 6891

To replace # with text

string s = "test # again";
s = s.Replace("#", "Superman");

To replace space with another character

string s = "test again";
s = s.Replace(' ', '#');

Upvotes: 0

Jonathan Wood
Jonathan Wood

Reputation: 67175

Sure, use the Replace() method.

s = s.Replace(" ", "#");

(And if you want people here to want to help you in the future, my recommendation would be to start accepting some answers. Just a thought.)

Upvotes: 8

Related Questions