libc/string: simplify strrchr

Do not call strlen() here. Old implementation iterated
over string twice, if searched for position was at the
beginning. This commit changes strrchr() to scan string
only once, regardless of input.

Signed-off-by: Juha Niskanen <juha.niskanen@haltian.com>
This commit is contained in:
Juha Niskanen 2022-05-10 15:02:40 +03:00 committed by Xiang Xiao
parent 0c8d3489e6
commit a17bfec43d
2 changed files with 7 additions and 6 deletions

View File

@ -39,7 +39,7 @@
* considered to be part of the string.
*
* Returned Value:
* Upon completion, strchrnull() returns a pointer to the byte, or a
* Upon completion, strchrnul() returns a pointer to the byte, or a
* pointer to null if the byte was not found.
*
****************************************************************************/

View File

@ -37,15 +37,16 @@
#undef strrchr /* See mm/README.txt */
FAR char *strrchr(FAR const char *s, int c)
{
FAR const char *p = &s[strlen(s)];
FAR const char *r = NULL;
for (; p >= s; p--)
do
{
if (*p == c)
if (*s == c)
{
return (FAR char *)p;
r = s;
}
}
while (*s++ != '\0');
return NULL;
return (FAR char *)r;
}