可能重复:
如何在 C# 中用单个空格替换多个空格?
如何修剪字符串中的空白最优雅的方法是" a<many spaces>b c "
into "a b c"
. 因此,重复的空格被缩小为一个空格。
可能重复:
如何在 C# 中用单个空格替换多个空格?
如何修剪字符串中的空白最优雅的方法是" a<many spaces>b c "
into "a b c"
. 因此,重复的空格被缩小为一个空格。
一个没有正则表达式的解决方案,只是为了把它放在桌子上:
char[] delimiters = new char[] { ' '}; // or null for 'all whitespace'
string[] parts = txt.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
string result = String.Join(" ", parts);
你可以用Regex
这个:
Regex.Replace(my_string, @"\s+", " ").Trim();
Regex.Replace(my_string, @"^\s+|\s+$|(\s)\s+", "$1");
使用该Trim
方法从字符串的开头和结尾删除空格,并使用正则表达式来减少多个空格:
s = Regex.Replace(s.Trim(), @"\s{2,}", " ");
Regex rgx = new Regex("\\s+");
string str;
str=Console.ReadLine();
str=rgx.Replace(str," ");
str = str.Trim();
Console.WriteLine(str);
Regex.Replace(str, "[\s]+"," ")
然后调用 Trim 删除前导和尾随空格。
使用正则表达式
String test = " a b c ";
test = Regex.Replace(test,@"\s{2,}"," ");
test = test.Trim();
此代码用一个空格替换任何 2 个或多个空格,Regex
然后在开头和结尾删除。
使用正则表达式:
"( ){2,}" //Matches any sequence of spaces, with at least 2 of them
并用它来用“”替换所有匹配项。
我还没有在 C# 中完成它,我需要更多时间来弄清楚文档所说的内容,所以你必须自己找到它......对不起。