簡體   English   中英

如何基於C#中字符串中元素的出現對數組進行排序?

[英]How to sort an array based on the occurrences of the elements in a string in C#?

我有一個數組

string [] country = {"IND", "RSA", "NZ", "AUS", "WI", "SL", "ENG", "BAN"};

我有一個弦

downloadString = "The match between India (IND) and Australia (AUS) is into its exciting phase. South Africa (RSA) won the match against England (ENG) "

所以我試圖找到字符串中存在哪些數組元素。 我能夠找到字符串中包含INDRSAAUSENG 但是,我無法根據它們在字符串中的出現順序對其進行排序。 所以現在我得到的輸出是

IND, RSA, AUS, ENG

而我真正需要的是

IND, AUS, RSA, ENG

我怎樣才能做到這一點?

另一種可能性是使用具有以下模式的正則表達式:

\b(IND|RSA|NZ|AUS|WI|SL|ENG|BAN)\b

演示版

示例代碼:(未經測試)

MatchCollection matches= System.Text.RegularExpresssion.Regex.Matches(yourStringSample, patternHere);

for each (Match m in matches)
{
   Debug.Print(m.ToString())
}

希望能幫助到你!

編輯:

基於下面的評論,我應該強調正則表達式模式應該使用類似如下的代碼構建:(如JLRishe所建議)

string pattern = "(" + string.Join("|", country.Select(c => Regex.Escape(c))) + ")"

您可以使用LINQ查詢簡潔做到這一點(我已經改名為原來的數組countries ):

var result = countries.Select(country => new { country, 
                                               index = downloadString.IndexOf(country)})
                      .Where(pair => pair.index >= 0)
                      .OrderBy(pair => pair.index)
                      .Select(pair => pair.country)
                      .ToArray();

結果是IND, AUS, RSA, ENG

您可以搜索字符串並保留找到的項目的位置,然后根據它們在字符串中的位置對其進行排序。 您可能需要一個結構數組來保留標簽和位置,而不是country數組!

暫無
暫無

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

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