Skip to main content
 首页 » 编程设计

c#之如何在 C# 中混合文本框中的单词顺序

2024年02月06日16zhoujg

我需要制作一个程序,在按下按钮时混合文本框中单词的顺序,但必须准确指定顺序。用户将句子放在文本框中,所以每次句子都不一样。顺序必须由偶数和奇数混合。假设这句话是“今天是美好的一天”。现在我们有 5 个单词,它们必须由奇数和偶数混合,所以顺序就像这样“day a today beautiful is”,因为偶数和奇数一起出现。 today [0], a [2] and day [4] 这些词有偶数,它们从最大到最小相互混合,所以它从 4 到 0。与奇数相同,但偶数优先(他们必须是第一个:4,2,0,3,1)。任何人都可以给我一个我如何做到这一点的例子吗?

请您参考如下方法:

您可以使用 LINQ-power:

string text = "today is a beautiful day"; 
var mixedWords = text.Split()                     // split by white-spaces 
    .Select((word, index) => new { word, index }) // select anonymous type 
    .GroupBy(x => x.index % 2)                    // remainder groups to split even and odd indices 
    .OrderBy(xg => xg.Key)                        // order by even and odd, even first 
    .SelectMany(xg => xg                          // SelectMany flattens the groups 
        .OrderByDescending(x => x.index)          // order by index descending 
        .Select(x => x.word));                    // select words from the anonymous type 
string newText = string.Join(" ", mixedWords);    // "day a today beautiful is"