Find last index of a character in a string | Simple CPP program to find last index of character x in given string . ; Returns last index of x if it is present . Else returns - 1. ; Traverse from right ; Driver code
#include <iostream> NEW_LINE using namespace std ; int findLastIndex ( string & str , char x ) { for ( int i = str . length ( ) - 1 ; i >= 0 ; i -- ) if ( str [ i ] == x ) return i ; return -1 ; } int main ( ) { string str = " geeksforgeeks " ; char x = ' e ' ; int index = findLastIndex ( str , x ) ; if ( index == -1 ) cout << " Character ▁ not ▁ found " ; else cout << " Last ▁ index ▁ is ▁ " << index ; return 0 ; }