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

Hello learners, today we are going to learn a very interesting topic that is: Find the last index of a character in a string in C++. This type of concept will be useful at the time coding competitions.

For example, the string is “code speedy” we need to get the last index of a character in a string. Suppose the character is ‘e’ we need to start searching the character from left to right. And return the last index of character that is ‘8’. Remember that in string space will also come in the count.

C++: Program Find the last index of a character in a string

Now we will see how the code runs for this program,

Code:

#include<iostream>
using namespace std;
int lastindexcalculation(string &str, char ch) 
  {
   int lastindex=-1;
   for (int i=0;i<str.length();i++)
      if (str[i] == ch)
        lastindex=i;
    return lastindex;
  }
  int lastindexcalculationleft(string &str, char ch) 
  {
      for (int i = str.length() - 1; i >= 0; i--)
      if (str[i] == ch)
    return i;
  }
int main() {
   string str = "code speedy";
   char ch;
   int n;
   cout<<"enter the character to get the last index:";
   cin>>ch;
   int lastindex = lastindexcalculation(str, ch);
   if (lastindex == -1)
      cout<<"Character not found";
   else
      cout<<"Last index of "<<ch<<" is "<<lastindex;
return 0;
}

Output: 1)

enter the character to get the last index:e
Last index of e is 8

Suppose entered character is not found from the string the output will be like this,

Output: 2)

enter the character to get the last index:a
Character not found

If you have any doubts, please ask your queries in the comment section below.

Also read: Find recurring sequence of a fraction in C++

One response to “Find last index of a character in a string in C++”

  1. AKASH RANJAN - says:

    Helpful, thanks for sharing sai……….

Leave a Reply

Your email address will not be published. Required fields are marked *