I have an string;
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 must return ipad
because ipad is in the first match ipad at the string.
In other case
String uA = "Mozilla/5.0 (iPhone/iPad; CPU OS 8_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12D508";
Same string array first match to iPhone
.
Strings can also be compared using the equality operator. Therefore, we can convert the arrays to strings, using the Array join() method, and then check if the strings are equal.
You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.
Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.
The strcmp() function, is used to compare the strings (str1,str2). The strings str1 and str2 will be compared using this function. If the function returns a value 0, it signifies that the strings are equal otherwise, strings are not equal.
So you want the word within the array which occurs earliest in the target string? That sounds like you might want 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();
Those steps in detail:
string.IndexOf
returns -1 if it's not found)null
if the sequence is emptyTry this:
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;
here is a none linq method to do that,
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With