In this post, we'll discuss two different ways to find the last occurrence of a character in a string using C#.
1) Using LastIndexOf() Method
The easiest method to find the last occurrence of a character in a string is using the LastIndexOf() method.
string data = "Hello World";
int lastIndex = data.LastIndexOf('o');
Console.WriteLine("The last index is: " + lastIndex);
If you want to perform a case-insensitive comparison, use this code instead.
string data = "Hello World";
int lastIndex = data.LastIndexOf("o", StringComparison.OrdinalIgnoreCase);
Console.WriteLine("The last index is: " + lastIndex);
2) Manually Finding the Last Occurrence
This is how we can manually find the last occurrence of a character.
string data = "Hello World";
char charToSearch = 'o';
int lastIndex = 0;
for (int i = 0; i < data.Length; i++)
{
if (data[i] == charToSearch)
{
lastIndex = i;
}
}
Console.WriteLine("The last index is: " + lastIndex);
For case-insensitive search:
string data = "Hello World";
char charToSearch = 'o';
int lastIndex = 0;
//charToSearch = char.ToLower(charToSearch);
for (int i = 0; i < data.Length; i++)
{
char chr = char.ToLower(data[i]);
if (chr == charToSearch)
{
lastIndex = i;
}
}
Console.WriteLine("The last index is: " + lastIndex);
Happy coding 👍.
Subscribe
Join the newsletter to get the latest updates.