Find a character in a String using C#

In this article we will discuss about how to find a character in a string in C#.
  • 9351

The IndexOf and LastIndexOf methods can be used to find an index of a character within a string. The IndexOf 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 in the string.

The LastIndexOf 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 IndexOf and LastIndexOf 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";
.WriteLine("Index of first 'a': " + authorName.IndexOf('a'));
Console.WriteLine("Index of 'a' after 5th char: " + authorName.IndexOf('a', 5));
Console.WriteLine("Index of 'a' after 10th char till next 5: " + authorName.IndexOf('a', 10, 5)); Console.WriteLine("Last index of 'a': " + authorName.LastIndexOf('a'));
Console.WriteLine("Last index of 'a': " + authorName.LastIndexOf('a', 5));
Console.WriteLine("Last index of 'a': " + authorName.LastIndexOf('a', 10, 5));

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


More Articles

© 2020 DotNetHeaven. All rights reserved.