OneBite.Dev - Coding blog in a bite size

Find The Last Occurrence Of A Character In A String In C#

Code snippet for how to Find The Last Occurrence Of A Character In A String In C# with sample and detail explanation

In the realm of programming, especially when you are dealing with text data, there are numerous occasions where you may need to locate the position of a specific character within a string. In C#, one of such occurrences could be finding the last occurrence of a character in a string. This is quite a common task, and if you are a beginner in C#, then this article will guide you on how to find the last occurrence of a character in a string in C#.

Code Snippet for Finding the Last Occurrence of a Character in a String

The following code snippet can be used to find the last occurrence of a specific character within a string in C#.

    string str = "Programming is fun";
    char ch = 'm';

    int lastIndex = str.LastIndexOf(ch);
    
    Console.WriteLine("Last occurrence is at index " + lastIndex);

Code Explanation for Finding the Last Occurrence of a Character in a String

In this tutorial, I will step you through the process of understanding the C# code snippet provided above.

  1. The code starts by declaring a string variable 'str' and initializes it to the sentence “Programming is fun”,
    string str = "Programming is fun";
  1. The next line of the C# code declares a character variable named ‘ch’ and initializes it to the character ‘m’,
    char ch = 'm';
  1. In the very next line, we make use of the “LastIndexOf()” function that is built into the C# language to find the position of the last occurrence of a specific character within a string. Here, ‘ch’ (i.e., ‘m’) is the character we are interested in and ‘str’ is the string in which we are searching for the character. The output of “LastIndexOf()” method is an integer that represents the position/index from the start of the string where the specified character last appears,
    int lastIndex = str.LastIndexOf(ch);
  1. Finally, the index of the last occurrence of the character is displayed to the console using the “Console.WriteLine()” method. If the character is not found in the string, the method will return -1,
    Console.WriteLine("Last occurrence is at index " + lastIndex);

The “LastIndexOf()” function is quite useful for finding the last occurrence of a character in a string in C#. It provides a simple and effective solution to one of the more common text processing tasks you’ll come across in programming with C#.

c-sharp