如何使用C#删除两个单词之间的额外空格?考虑:
"Hello World"
我希望将其作为"Hello World"
进行操作。
答案 0 :(得分:52)
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(@"[ ]{2,}", options);
tempo = regex.Replace(tempo, @" ");
甚至:
myString = Regex.Replace(myString, @"\s+", " ");
均来自here
答案 1 :(得分:13)
var text = "Hello World";
Console.WriteLine(String.Join(" ", text.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)));
答案 2 :(得分:10)
您可以将选项传递给String.Split(),告诉它折叠连续的分隔符,以便您可以写:
string expr = "Hello World";
expr = String.Join(" ", expr.Split(new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries));
答案 3 :(得分:1)
var text = "Hello World";
Regex rex = new Regex(@" {2,}");
rex.Replace(text, " ");
答案 4 :(得分:1)
string str = "Hello World";
Regex exper=new Regex(@"\s+");
Console.WriteLine(exper.Replace(str, @" "));
答案 5 :(得分:0)
在ASP中的字符串之间清除多余的空间。 NET C#
假设:一个名字叫JITENDRA KUMAR 而且我在名字和转换字符串之间有清晰的间距:JITENDRA KUMAR; 然后遵循此代码:
string PageName= "JITENDRA KUMAR";
PageName = txtEmpName.Value.Trim().ToUpper();
PageName = Regex.Replace(PageName, @"\s+", " ");
Output string Will be : JITENDRA KUMAR
答案 6 :(得分:-2)
试试这个:
string helloWorldString = "Hello world";
while(helloWorldString.Contains(" "))
helloWorldString = helloWorldString.Replace(" "," ");