The most efficient way to find the last char

Consider this function, I quickly wrote to find the last occurrence of a given char in a string and return it to an array of characters, which is physically a string:

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

I just typed it here very quickly (I have not compiled or noticed yet) because I have questions about a few things.

For me, this seems like the simplest solution for finding which element of an array contains the last instance of a specific char, but I don't know how this works. I just did this after the strrchr documentation, so technically strrchr does all the work. I just can't imagine that this is the best way (in terms of performance) to achieve this, and was hoping that someone could make some contribution to what would be the best way to do this.

Is strrchr an effective way to do this? Or is strrchr best left to other use?

+5
source share
3 answers

The approach you used is perfectly fine - unfortunately, array operations are expensive. Strrchr in most implementations just goes through the string, starting at the end, until it finds the corresponding character. This is the time O(n). Then you do the subtraction O(1). It's not so bad.

+4
source

From the docs:

Returns a pointer to the last occurrence of a character in a string of string C.

Thus, he does exactly what you want. The purpose of his existence is as follows.

Is strrchr an effective way to do this?

, .

strrchr ?

. .

+3

It will be faster if you can specify the length of the string and then just loop back. When you immediately find that the first occurrence of a character is returned.

If you don't know the length, just use strrchr.

0
source

All Articles