简体   繁体   English

如何用其他东西替换字符串中的字符?

[英]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? C#中是否有任何命令可以让我做到这一点而无需遍历整个字符串?

Sure, use the Replace() method. 当然,请使用Replace()方法。

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. 您是否尝试过使用string对象的Replace方法 This will do the trick: 这将达到目的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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