简体   繁体   中英

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

I have got an array

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

I have a string

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

So I am trying to find which of the array elements are present in the string. I am able to find that IND , RSA , AUS and ENG are present in the string. However, I am unable to order them according to their occurrence in the string. So right now the output which I get is

IND, RSA, AUS, ENG

Whereas, what I really need is

IND, AUS, RSA, ENG

How can I do that?

Another possibility is to use regex with the following pattern:

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

Demo

Sample Code: (untested)

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

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

Hope it helps!

EDIT:

Based on the comment below, I should highlight that the regex pattern should build using similar code like below: (as suggested by JLRishe)

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

You can do this concisely with a Linq query (I've renamed your original array to 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();

The result is IND, AUS, RSA, ENG .

You can search the string and keep the position of the found item, then sort them according to their position in string. You may need an array of a structure to keep both the label and position instead of the country array!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM