Search code examples
cperformancestrrchr

Most efficient way of finding last char occurrence


Consider this function I wrote real quick to find the last occurrence of a given char in a string and return it's position within the array of chars that physically is the string:

size_t strlstchar(const char *str, const char ch)
{
    char *chptr = strrchr(str, ch);
    return chptr - str;
}

I just typed this up real quick here (haven't compiled or anyting yet) just because I have questions about a few things.

To me this seems like the simplest solution to find which array element holds the last instance of a particular char, but I have no idea how it works. I just made this following the documentation of strrchr, so it's technically strrchr doing all the work. I just can't imagine this being the best way (in terms of performance) to achieve this, and was hoping somebody could give some input on what would be the best way to do this.

Is strrchr an efficient way to do this? Or is strrchr best left for some other use?


Solution

  • The approach you used is perfectly fine - unfortunately, array operations are expensive. Strrchr in most implementations simply steps through the string beginning from its end until it finds a matching character. That's O(n) time. Then you perform a subtraction which is O(1). This is not that bad.