c#如何去掉中间的空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9941932/
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
how to remove space in the middle using c#
提问by Kalaivani
how to remove space in the middle using c#? I have the string name="My Test String"and I need the output of the string as "MyTestString"using c#.
Please help me.
如何使用c#删除中间的空格?我有string name="My Test String"并且我需要"MyTestString"使用 c#的字符串输出。请帮我。
回答by Sai Kalyan Kumar Akshinthala
Write like below
像下面这样写
name = name.Replace(" ","");
回答by Sunil Chavan
using System;
using System.Text.RegularExpressions;
class TestProgram
{
static string RemoveSpaces(string value)
{
return Regex.Replace(value, @"\s+", " ");
}
static void Main()
{
string value = "Sunil Tanaji Chavan";
Console.WriteLine(RemoveSpaces(value));
value = "Sunil Tanaji\r\nChavan";
Console.WriteLine(RemoveSpaces(value));
}
}
回答by CSharpCoder
Fastest and general way to do this (line terminators, tabs will be processed as well). Regex powerful facilities don't really needed to solve this problem, but Regex can decrease performance.
执行此操作的最快和通用方法(行终止符,制表符也将被处理)。解决这个问题并不真正需要正则表达式强大的工具,但正则表达式会降低性能。
new string
(stringToRemoveWhiteSpaces
.Where
(
c => !char.IsWhiteSpace(c)
)
.ToArray<char>()
)

