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

风格不统一 提交于 2020-01-06 05:25:16

问题


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?


回答1:


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




回答2:


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



回答3:


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




回答4:


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

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


来源:https://stackoverflow.com/questions/5242323/how-can-i-replace-a-character-in-a-string-with-something-else

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!