如何在 C# 中用下划线替换字符串中的空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9003172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:32:18  来源:igfitidea点击:

How can I replace a space in a string with an underscore in C#?

c#

提问by Jessica

I have strings such as:

我有字符串,例如:

var abc = "Menu Link";

Is there a simple way I can change the space to an underscore?

有没有一种简单的方法可以将空格更改为下划线?

采纳答案by Yuck

If you want to do it in place:

如果你想就地做:

abc = abc.Replace(" ", "_");

Although do realize a newstringinstance will be created; it's not actually done in the same memory location - Stringis an immutable type.

尽管确实意识到将创建一个string实例;它实际上不是在同一个内存位置完成的 -String是一种不可变的类型。

回答by cdiggins

Using String.Replace(char,char)instead of String.Replace(string, string)should be much faster. i.e.

使用String.Replace(char,char)而不是String.Replace(string, string)应该快得多。IE

abc = abc.Replace(' ', '_');

回答by Aishwar C Nigam

simply add .Replace()function at the end of the string.

只需.Replace()在字符串末尾添加函数即可。

abc = abc.Replace(' ', '_');