簡體   English   中英

如何在C#中的文本框中混合單詞順序?

[英]How can I mix the order of words in a textbox in C#?

我需要制作一個程序,當按下按鈕時,該程序會混合文本框中的單詞順序,但是必須准確指定順序。 用戶將句子放在文本框中,因此每次句子都不同。 該順序必須由偶數和奇數混合。 可以說這句話是“今天是美好的一天”。 現在我們有5個單詞,並且它們必須由奇數和偶數混合,因此順序就像今天的“今天是美好的一天”,因為偶數和奇數並存。 今天[0],a [2]和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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM