如何用c#中的一个空格替换字符串中的多个空格?
例子:
1 2 3 4 5
是:
1 2 3 4 5
如何用c#中的一个空格替换字符串中的多个空格?
例子:
1 2 3 4 5
是:
1 2 3 4 5
当前回答
使用正则表达式模式
[ ]+ #only space
var text = Regex.Replace(inputString, @"[ ]+", " ");
其他回答
老派:
string oldText = " 1 2 3 4 5 ";
string newText = oldText
.Replace(" ", " " + (char)22 )
.Replace( (char)22 + " ", "" )
.Replace( (char)22 + "", "" );
Assert.That( newText, Is.EqualTo( " 1 2 3 4 5 " ) );
string xyz = "1 2 3 4 5";
xyz = string.Join( " ", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));
// Mysample string
string str ="hi you are a demo";
//Split the words based on white sapce
var demo= str .Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
//Join the values back and add a single space in between
str = string.Join(" ", demo);
// output: string str ="hi you are a demo";
混合StringBuilder和Enumerable.Aggregate()作为字符串的扩展方法:
using System;
using System.Linq;
using System.Text;
public static class StringExtension
{
public static string CondenseSpaces(this string s)
{
return s.Aggregate(new StringBuilder(), (acc, c) =>
{
if (c != ' ' || acc.Length == 0 || acc[acc.Length - 1] != ' ')
acc.Append(c);
return acc;
}).ToString();
}
public static void Main()
{
const string input = " (five leading spaces) (five internal spaces) (five trailing spaces) ";
Console.WriteLine(" Input: \"{0}\"", input);
Console.WriteLine("Output: \"{0}\"", StringExtension.CondenseSpaces(input));
}
}
执行这个程序产生以下输出:
Input: " (five leading spaces) (five internal spaces) (five trailing spaces) "
Output: " (five leading spaces) (five internal spaces) (five trailing spaces) "
我知道这很老了,但在尝试完成几乎相同的事情时偶然发现了它。在RegEx Buddy中找到了这个解决方案。该模式将用单个空格替换所有的双空格,并修剪开头和结尾空格。
pattern: (?m:^ +| +$|( ){2,})
replacement: $1
因为我们处理的是空格,所以读起来有点困难,所以这里还是用“_”代替了“空格”。
pattern: (?m:^_+|_+$|(_){2,}) <-- don't use this, just for illustration.
“(?M:" construct启用“多行”选项。我通常喜欢在模式本身中包含任何我可以包含的选项,这样它就更独立了。