Mark Mark - 26 days ago 8
C++ Question

Return a pointer to the last appearance of a character in a C-Style string (C++)

Return a pointer to the last appearance of c
appearing inside s and nullptr (0) if c does not appear inside s.

#include <string>
#include <iostream>
#include <cassert>
using namespace std;

const char* myStrRChr(const char* s, char c)
{
int curIdx = 0;
char last;

while (s[curIdx] != '\0')
{
if (s[curIdx] == c)
last = s[curIdx];
curIdx++;
}
if (s[curIdx] == c)
return last;
else
// return '\0', nullptr, NULL
return "";
}


int main()
{
char cstr[50] = "Abadabadoo!";
char buf[10];
const char * cat = "cat";
char dog[] = "Labradoodle";

cout << "\nmyStrRChr(cstr, 'a') expects adoo!" << endl;
cout << " -- " << myStrRChr(cstr, 'a') << endl;

return 0;
}


This code returns "adabadoo!". I can't wrap my mind around as to how to get the last instance of "char c."

Answer

You can do this by obtaining a pointer to the end of the string and decrementing down the string searching for the character c, and a pointer to the beginning of the string to know where to stop looping:

const char *mystrrchr(const char *str, char c)
{
    int len = strlen(str);
    char *p = const_cast<char *>(&str[len-1]);
    char *stop = const_cast<char *>(&str[0]);
    while(p>=stop)
    {
        if(*p==c)
        {
            return p;
        }
        p--;
    }
    return nullptr;
}