Find last index of a character in a string in C++

C++Server Side ProgrammingProgramming

Suppose we have a string str. We have another character ch. Our task is to find the last index of ch in the string. Suppose the string is “Hello”, and character ch = ‘l’, then the last index will be 3.

To solve this, we will traverse the list from right to left, if the character is not same as ‘l’, then decrease index, if it matches, then stop and return result.

Example

#include<iostream>
using namespace std;
int getLastIndex(string& str, char ch) {
   for (int i = str.length() - 1; i >= 0; i--)
      if (str[i] == ch)
         return i;
   return -1;
}
int main() {
   string str = "hello";
   char ch = 'l';
   int index = getLastIndex(str, ch);
   if (index == -1)
      cout << "Character not found";
   else
      cout << "Last index is " << index;
}

Output

Last index is 3
raja
Published on 01-Nov-2019 14:49:59
Advertisements