Find any character in a String using C#

In this article we will find any character in a string in C#.
  • 6314

The IndexOfAny and LastIndexOfAny methods can be used to find an index of any character of an array of characters within a string. The IndexOfAny method returns the 0 based index of the first occurrence of a character. If a character is found, it returns the index of the character; otherwise returns -1.

This method has several overloaded forms and hence can be applied on the entire string or a portion of the string by specifying the start and end positions of characters within a string.
The LastIndexOfAny method returns the 0 based index of the last occurrence of a character found in a string.

The following code snippet uses various forms of IndexOfAny and LastIndexOfAny methods. As you can see from this code, we can even specify what part of a string you want to search for. The second parameter of IndexOf and LastIndexOf takes the starting index and third parameter is the number of characters after the starting index.


String authorName = "Mahesh Chand Beniwal";  
char[] findChars = new char[] { 'a', 'e', 'i', 'o', 'u'};
Console
.WriteLine(authorName.IndexOfAny(findChars));
Console.WriteLine(authorName.IndexOfAny(findChars, 5));
Console.WriteLine(authorName.IndexOfAny(findChars, 5, 5));
Console.WriteLine(authorName.LastIndexOfAny(findChars));
Console.WriteLine(authorName.LastIndexOfAny(findChars, 5));
Console.WriteLine(authorName.LastIndexOfAny(findChars, 5, 5));

 
Ask Your Question 
 
Got a programming related question? You may want to post your question here
 

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.