开发者

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

开发者 https://www.devze.com 2023-02-16 03:55 出处:网络
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.

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 the开发者_如何学JAVAre any command in C# that lets me do this without looping through the whole string?


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.)


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(' ', '#');


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


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

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

精彩评论

暂无评论...
验证码 换一张
取 消