从字符串中删除交替的空格

时间:2016-10-28 15:43:22

标签: c# string replace

如何从字符串中删除空格,但前提是它们是否与非空格相邻?

E.g。我想将P u m p k i n p i e变成Pumpkin pie

我目前的String.Join("", input.Split(' '));解决方案不会保留上述示例中的空格。

4 个答案:

答案 0 :(得分:2)

一种方法是匹配空格,后跟非空格或2 +空格,并用空字符串替换它们:

using System.Text.RegularExpressions;
...
var str = "P u m p k i n   p i e";
var res = Regex.Replace(str, @"\s(?=\S|\s{2,})", "");

Demo of the regex.

Demo of the program.

答案 1 :(得分:0)

我并不以此为荣,但如果你不喜欢正则表达式。

string[] splitters = new string[] { "  " };
string input = "P u m p k i n   p i e";
string output = String.Join(" ", input.Split(splitters, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Replace(" ", String.Empty)));

答案 2 :(得分:0)

怎么样:

string text = "I    l o v e   P u m p k i n                p i e";

// Use a special character for word delimiter. In this specific case, #
string result = Regex.Replace(text, @"\s{2,}", "#");

// Get the words
IEnumerable<string> words = result.Split('#').Select(w => String.Join(String.Empty, w.Split(' ')));

// Join the words with space character
result = String.Join(" ", words);

最终结果为"I love pumpkin pie"

如果你喜欢单行:

string result = String.Join(" ",
        Regex.Replace(text, @"\s{2,}", "#")
        .Split('#')
        .Select(w =>
            String.Join(String.Empty, w.Split(' '))));

答案 3 :(得分:0)

string input = "P u m p k i n   p i e";
string output = Regex.Replace(input, "(?<! ) (?! )", "");
output = Regex.Replace(output, " {2,}", " ");