简体   繁体   中英

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?

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

请确保从Replace()方法检索返回的字符串,因为它不会更改原始字符串...它将生成一个新的字符串。

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM