C# String LastIndexOfAny()

The LastIndexOfAny() method in C# is used to search for the last occurrence of any character from a specified array of characters within a string. It returns the zero-based index of the last occurrence of any character from the array, or -1 if no such character is found.

Here’s the syntax of the LastIndexOfAny() method:

public int LastIndexOfAny(char[] anyOf)

Parameters:

  • anyOf: An array of Unicode characters to search for.

Return Value:

  • The zero-based index position of the last occurrence of any character from the anyOf array within the string, if found; otherwise, -1.

Example usage:

string text = "Hello, world!";
char[] searchChars = { 'o', 'l' };

int lastIndex = text.LastIndexOfAny(searchChars);
Console.WriteLine(lastIndex);  // Output: 10

In the above example, the LastIndexOfAny() method is called on the text string with the searchChars array as the argument. It searches for the last occurrence of either ‘o’ or ‘l’ in the string and returns the index position, which is 10 in this case.

C# String LastIndexOfAny() Method Example:

Certainly! Here’s an example that demonstrates the usage of the LastIndexOfAny() method in C#:

using System;

class Program
{
    static void Main()
    {
        string text = "Hello, world!";
        char[] searchChars = { 'o', 'l' };

        int lastIndex = text.LastIndexOfAny(searchChars);
        
        if (lastIndex != -1)
        {
            Console.WriteLine("Last occurrence found at index: " + lastIndex);
            Console.WriteLine("Last occurrence character: " + text[lastIndex]);
        }
        else
        {
            Console.WriteLine("No matching character found.");
        }
    }
}

In this example, we have a string text containing the phrase “Hello, world!” and an array searchChars containing characters ‘o’ and ‘l’. We call the LastIndexOfAny() method on the text string, passing the searchChars array as the argument.

The LastIndexOfAny() method returns the index of the last occurrence of any character from the searchChars array within the string. We store this index in the lastIndex variable.

We then check if the lastIndex is not equal to -1, which indicates that a matching character was found. If a match is found, we display the index of the last occurrence and the corresponding character. Otherwise, we display a message indicating that no matching character was found.

When you run this code, it will output:

Last occurrence found at index: 10
Last occurrence character: o

This means that the last occurrence of either ‘o’ or ‘l’ in the string is at index 10, and the character at that index is ‘o’.