C# IndexOfAny

Any method

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

Note

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.

And:The first argument 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.

Char Array
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

The IndexOfAny method is invoked twice. 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.

Next:The second method call has the same parameter value and it locates the uppercase B in its source string.

Overloads

Three

This method has three overloads. 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.

Tip:The IndexOfAny method always performs a forward-only (left to right) scan of the input string.

But:You can use the LastIndexOfAny method for a reversed scan. This method is described in more detail.

LastIndexOfAny

Summary

Framework: NET

We looked at the IndexOfAny method in the C# language targeting the .NET Framework. This method provides a way to scan an input string declaratively for the first occurrence of any of the characters in the parameter char array.

So:IndexOfAny reduces loop nesting. It reduces general program complexity. It is worth considering in many situations.


C#: String