[英]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) "
所以我试图找到字符串中存在哪些数组元素。 我能够找到字符串中包含IND
, RSA
, AUS
和ENG
。 但是,我无法根据它们在字符串中的出现顺序对其进行排序。 所以现在我得到的输出是
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.