簡體   English   中英

如何在C#中比較字符串和字符串數組?

[英]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();

這些步驟詳細:

  • 將單詞投影到一個單詞/索引對序列中,其中索引是目標字符串中該單詞的索引
  • 通過刪除索引為-1的對來省略目標字符串中沒有出現的單詞(如果找不到,則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.

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