Reputation: 13
Is there any function that returns the index of the first occurrence of ANY string in a given array like: String.IndexOf(String[])
?
or do I need a custom function for it?
For example the below function
"AppleBananaCherry".IndexOf(new[] {"Banana", "Cherry"});
and
"AppleBananaCherry".IndexOf(new[] {"Cherry", "Banana"});
returns 5
Upvotes: 0
Views: 647
Reputation: 23228
There is no built-in function for that, String.IndexOf()
method accepts only single string or char
as parameter, but you can write your own extension method, which uses IndexOf
for every item in array, like in the following sample. It also should correctly exclude -1
from intermediate result
public static class Ext
{
public static int IndexOf(this string thisString, string[] values)
{
var index = thisString.Length;
var isFound = false;
foreach (var item in values)
{
var itemIndex = thisString.IndexOf(item, StringComparison.InvariantCulture);
if (itemIndex != -1 && itemIndex < index)
{
index = itemIndex;
isFound = true;
}
}
return isFound ? index : -1;
}
}
The usage example
var index = "AppleBananaCherry".IndexOf(new[] {"Banana", "Cherry"}); //returns 5
index = "AppleBananaCherry".IndexOf(new[] { "Cherry", "Banana" }); //returns 5
Upvotes: 1
Reputation: 140
This should
public static int IndexOf(this string s, string[] values) {
var found = values
.Select(v => s.IndexOf(v))
.Where(index => index >= 0)
.OrderBy(v => v)
.Take(1)
.ToList();
return found.Count > 0 ? found[0] : -1;
}
EDIT: Removing -1 values
Upvotes: 1
Reputation: 1416
There is no prepared function but you can use something like this,
var sample = "AppleBananaCherry";
var input = new[] { "Cherry", "Banana" };
var result = input.Min(x => sample.IndexOf(x));
If sample has not any item of input, it returns -1
Upvotes: 2