C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: The first argument is a character array, which you can declare directly in the parameter list or separately as a variable.
Tip: It is sometimes faster to store this char array separately and reuse it whenever calling IndexOfAny.
Char ArrayFirst: The first call searches for a lowercase e or an uppercase B. It finds the lowercase e because it comes first in the string.
Next: The second method call has the same parameter value and it locates the uppercase B in its source string.
C# program that uses IndexOfAny method
using System;
class Program
{
static void Main()
{
// Input.
const string value1 = "My cat eats fish.";
const string value2 = "Visual Basic is hard.";
// Find first location of 'e' or 'B'.
int index1 = value1.IndexOfAny(new char[] { 'e', 'B' });
Console.WriteLine(value1.Substring(index1));
// Find first location of 'e' or 'B'.
int index2 = value2.IndexOfAny(new char[] { 'e', 'B' });
Console.WriteLine(value2.Substring(index2));
}
}
Output
eats fish.
Basic is hard.
Results: The IndexOfAny method seems to perform much worse than a for-loop with an if-statement. For a simple search, it is far slower.
ForIfHowever: If an array of characters is needed, the IndexOfAny method's performance will likely be more competitive.
C# program that benchmarks IndexOfAny
using System;
using System.Diagnostics;
class Program
{
const int _max = 1000000;
static void Main()
{
string test = "abcdefg";
// Version 1: test IndexOfAny.
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
int result = test.IndexOfAny(new char[] { 'd', 'x', '?' });
if (result != 3)
{
return;
}
}
s1.Stop();
// Version 2: test custom loop with if-statement.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
int result = -1;
for (int x = 0; x < test.Length; x++)
{
if (test[x] == 'd' || test[x] == 'x' || test[x] == '?')
{
result = x;
break;
}
}
if (result != 3)
{
return;
}
}
s2.Stop();
Console.WriteLine(s1.Elapsed.TotalMilliseconds);
Console.WriteLine(s2.Elapsed.TotalMilliseconds);
}
}
Output
36.7644 ms IndexOfAny
6.175 ms For-loop
Arguments: The 2 values indicate the position in the source string you want to begin searching, and then the number of characters to check.