C# IndexOfAny

IndexOf illustration

IndexOfAny searches a string for many values. It returns the first position of any of the values you provide. The .NET Framework provides several overloads of IndexOfAny. This method is useful in certain contexts.

Example

The IndexOfAny method is closely related to the IndexOf method on the string type. It is an instance method that returns an integer value type indicating the position of the found character, or the special value -1 if no value was found. The first parameter to IndexOfAny is a character array, which you can declare directly in the parameter list or separately as a variable.

IndexOf

Tip: It is sometimes faster to store this char[] array separately and reuse it whenever calling IndexOfAny.

Program that uses IndexOfAny method [C#]

using System;

class Program
{
    static void Main()
    {
	// A.
	// Input.
	const string value1 = "Darth is my enemy.";
	const string value2 = "Visual Basic is hard.";

	// B.
	// Find first location of 'e' or 'B'.
	int index1 = value1.IndexOfAny(new char[] { 'e', 'B' });
	Console.WriteLine(value1.Substring(index1));

	// C.
	// Find first location of 'e' or 'B'.
	int index2 = value2.IndexOfAny(new char[] { 'e', 'B' });
	Console.WriteLine(value2.Substring(index2));
    }
}

Output

enemy.
Basic is hard.
Main method

Description. The IndexOfAny method is invoked twice in the method body. The source string is different in both invocations. The first call searches for a lowercase 'e' or an uppercase 'B', and it finds the lowercase 'e' because it comes first in the source string. The second method call has the same parameter value and it locates the uppercase 'B' in its source string.

Method overloads

Programming tip

Here we note that the IndexOfAny method on the string type in the C# programming language provides three overloaded versions for you to choose from. You can provide the startIndex and the count parameter integer values. These two values indicate the position in the source string you want to begin searching, and then the number of characters to check. The IndexOfAny method always performs a forward-only (left to right) scan of the input string. You can use the LastIndexOfAny method for a reversed scan.

LastIndexOfAny

Summary

.NET Framework information

We looked at the IndexOfAny method in the C# programming language targeting the .NET Framework, which provides a way to scan an input string declaratively for the first occurrence of any of the characters in the parameter char[] array. Because this method call can reduce loop nesting and general complexity in your program, the IndexOfAny method, along with the other IndexOf methods, is worth considering in many situations.

String Type
.NET