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

Finding the last occurrence of a character in a C++ string is a common operation in software development. This article provides an easy way to achieve this using standard C++ libraries, includes a detailed code snippet and an explanation of how the code works.

Code Snippet

Here is a simple code snippet that finds the last occurrence of a specific character in a string:

#include <iostream>
#include<string.h>
using namespace std;

int main() {
    string inputString = "This is a simple test.";
    char searchChar = 's';
    int lastPosition = inputString.find_last_of(searchChar);
    if (lastPosition!=string::npos)
      cout << "The last occurrence of " << searchChar << " is at position: " << lastPosition << endl;
    else
      cout << "Character not found!" << endl;
    return 0;
}

Code Explanation

Following is a step-by-step explanation of how this C++ code snippet works:

  1. First, the required libraries are included. The iostream library is used to handle input/output operations and the string library provides features to work with string data types.

  2. The using namespace std; statement allows the program to use entities that are part of the std namespace.

  3. Inside the main function, an example string inputString is defined to search within. This string can be replaced with any string of your choice.

  4. A character searchChar is declared which is the character we are searching for in the string.

  5. The find_last_of function is called on inputString with searchChar as the parameter. This function is built-in with C++ string and it returns the index of the last occurrence of the character that is passed as a parameter. If the character is not found, it returns string::npos.

  6. An if statement checks whether lastPosition is not equal to string::npos (which means the character was found). If true, it prints the position of the last occurrence of the character else it prints “Character not found!“.

Remember that string index in C++ starts from 0. Therefore, if you have a string “Hello” and you are checking position of ‘o’, it will return 4, not 5.

In summary, the find_last_of function is a base method in C++, which provides an easy way to find the last occurrence of a character in a string. This approach makes the C++ string processing more efficient and convenient.

c-plus-plus