用c#中的新行替换空格的奇数出现的Sweet and Short方法

本文关键字:Sweet and Short 方法 新行 替换 空格 | 更新日期: 2023-09-27 18:20:56

假设我有一个字符串,如下所示:

string s = "My Name is Vishal.";

我想得到如下输出:

My Name
is Vishal.

我的意思是,如果出现的空格是2的倍数,我想用新行替换空格。

目前我正在使用以下代码来完成我的工作:

string[] sArray = s.Split(' ');
string x = "";
for (int i=0; i <= sArray.Length - 1; i++)
{
    if (i % 2 == 0)
        x += sArray[i] + ' ';
    else
        x += sArray[i] + Environment.NewLine;
}
return x;

上面的代码运行良好,但我知道会有一个好的方法来做。有人能给我一个好方法吗?

用c#中的新行替换空格的奇数出现的Sweet and Short方法

如果你坚持的话,只有一行,尽管我已经把它分解了。它使用Split(),因此多个空间被视为一个空间。

string.Join(
    Environment.NewLine,
    s.Split()
        .Select((ss, i) => new { ss, i })
        .GroupBy(
            p => p.i / 2,
            (k, ps) => string.Join(" ", ps.Select(p => p.ss))));

Regex替代品。这一个将空间组视为单个空间,但在奇数情况下不会用单个空间替换它们。

Regex.Replace(s, "(?<=^((?:[^ ]+ +){2})*[^ ]+ +[^ ]+) +", Environment.NewLine)

这将单独处理一组多个空间中的每个空间。

Regex.Replace(s, "(?<=^((?:[^ ]* ){2})*[^ ]* [^ ]*) ", Environment.NewLine)

这不是恒星,但它足够有趣,我写下来:)

string s1 = "My Name is Vishal.";
string s2 = "My Name is not Vishal.";
var input = s1;
var list = input .Split(" ".ToCharArray()).ToList();
StringBuilder sb = new StringBuilder();
while (list.Any()) {
    var bits = list.Take(2);
    sb.Append(bits.First ());
    if (bits.Count() >1) {
        sb.AppendLine(" " + bits.Last());
        list.RemoveRange(0,2);
    }
    else
        list.RemoveAt(0);
}
var result = sb.ToString(); 

使用s1运行将为您提供

我的名字
是Vishal

使用s2运行将为您提供

我的名字
不是
Vishal

这是必需的LINQ版本,不确定它是否更可读:

string s = "My Name is Vishal.";
var lineGroups = s.Split()
    .Select((word, index) => new { word, index })
    .GroupBy(x => x.index / 2) // integer division truncates decimal part
    .Select(g => string.Join(" ", g.Select(x => x.word)));
string result = string.Join(Environment.NewLine, lineGroups);