[英]How to compare string to String Array in C#?
我有一個字符串;
String uA = "Mozilla/5.0 (iPad; CPU OS 8_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12D508 Twitter for iPhone";
String[] a= {"iphone","ipad","ipod"};
它必須返回ipad
因為ipad是第一個匹配ipad的字符串。 在其他情況下
String uA = "Mozilla/5.0 (iPhone/iPad; CPU OS 8_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12D508";
相同的字符串數組首先匹配iPhone
。
所以你想要在目標字符串中最早出現的數組中的單詞? 這聽起來像你可能想要的東西:
return array.Select(word => new { word, index = target.IndexOf(word) })
.Where(pair => pair.index != -1)
.OrderBy(pair => pair.index)
.Select(pair => pair.word)
.FirstOrDefault();
這些步驟詳細:
string.IndexOf
返回-1) null
試試這個:
String uA = "Mozilla/5.0 (iPad; CPU OS 8_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12D508 Twitter for iPhone";
String[] a = { "iphone", "ipad", "ipod" };
var result = a.Select(i => new { item = i, index = uA.IndexOf(i) })
.Where(i=>i.index >= 0)
.OrderBy(i=>i.index)
.First()
.item;
這是一個無linq方法來做到這一點,
static string GetFirstMatch(String uA, String[] a)
{
int startMatchIndex = -1;
string firstMatch = "";
foreach (string s in a)
{
int index = uA.ToLower().IndexOf(s.ToLower());
if (index == -1)
continue;
else if (startMatchIndex == -1)
{
startMatchIndex = index;
firstMatch = s;
}
else if (startMatchIndex > index)
{
startMatchIndex = index;
firstMatch = s;
}
}
return firstMatch;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.