2014-06-11 16 views
1

我需要製作一個程序,用於在按下按鈕時在文本框中混合單詞的順序,但必須精確指定順序。用戶在文本框中放置句子,所以句子每次都是不同的。訂單必須由偶數和奇數混合。讓我們說句子是「今天是美好的一天」。現在我們有5個單詞,它們必須用奇數和偶數混合,所以順序就像這樣:「今天美麗的日子」,因爲偶數和奇數會一起。今天[0],[2]和第[4]天這些詞有偶數,並且它們從最大到最小彼此混合,因此它從4變爲0.與奇數相同但偶數具有優先權他們必須是第一個:4,2,0,3,1)。任何人都可以給我一個我如何做到這一點的例子嗎?如何在C#中的文本框中混合單詞的順序?

+1

看起來像功課。你自己做過什麼嗎?這個任務有什麼問題? –

+0

@SergeyBerezovskiy是的,我自己完成了其餘的工作,我只是不知道如何編寫該程序的這個功能。我試圖用替換方法做一些事情,但我得到的只是錯誤。 – pikazzu

+0

我回滾了你的編輯 - 代碼與這個問題沒有關係 –

回答

4

您可以使用LINQ功率:

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" 
+0

很明顯,沒有任何努力從OP做這個功課.. –

+0

@SergeyBerezovskiy:如果它是作業我懷疑OP可以使用LINQ。 –

+0

@TimSchmelter感謝您的幫助,沒有這不是作業 – pikazzu

相關問題