[英]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. 我能够找到字符串中包含IND
, RSA
, AUS
和ENG
。 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
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) 基于下面的评论,我应该强调正则表达式模式应该使用类似如下的代码构建:(如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
): 您可以使用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();
The result is IND, AUS, RSA, ENG
. 结果是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! 您可能需要一个结构数组来保留标签和位置,而不是country数组!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.