How to compare string with String Array in C #?

I have a line;

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"}; 

It should return ipad , because ipad is in the first ipad match in string. Otherwise

 String uA = "Mozilla/5.0 (iPhone/iPad; CPU OS 8_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12D508"; 

The same array of strings first matches the iPhone .

+5
source share
3 answers

So, do you want the word inside the array to happen first in the target string? It looks like you might need something like:

 return array.Select(word => new { word, index = target.IndexOf(word) }) .Where(pair => pair.index != -1) .OrderBy(pair => pair.index) .Select(pair => pair.word) .FirstOrDefault(); 

These steps are in detail:

  • Project words into a sequence of word / index pairs, where the index is the index of that word in the target row
  • Omit words that did not appear on the target line by deleting pairs where the index is -1 ( string.IndexOf returns -1 if it is not found)
  • Sort by index to make the earliest word as first pair
  • Choose a word in each pair as we no longer need indexes
  • Return the first word or null if the sequence is empty
+10
source

Try the following:

  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; 
+1
source

there is no linq method for this,

  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; } 
+1
source

All Articles