Home > Software design >  Make own strrchr() function but case-insensitiv
Make own strrchr() function but case-insensitiv

Time:05-04

my exercise is to create my own strrchr() function in c.

My solution is a loop. I'am counting the array length. I will input this number into the for loop. For example: With the input Hello. I will go from right to left to search for a letter.

What's not working is the return part.

My code returns the following with the input Hello, and search letter l. lo. That's not what I need. My ouput should be lleH.

Any ideas what I did wrong?

    char *KULstrrcichr(char *arr, char search)

// The strrchr() function returns a pointer to the last occurrence of the character c in the string s.
{   
    int stringcnt;
    stringcnt = strlen(arr);
    printf("%d\n", stringcnt);
    search = tolower(search);
    for (int i = stringcnt-1; arr[i]; i--)
    {
        arr[i] = tolower(arr[i]);
    }
    for (int i = stringcnt-1; arr[i]; i--)
    {
        if (search == arr[i])
        {
            return &arr[i];
        }
    }
    return 0;
}

Okay I found out that my code works as expected...

CodePudding user response:

The standard C function strrchr is declared the following way

char *strrchr(const char *s, int c);

That is it first parameter has the qualifier const and the second parameter is of the type int. It means that you may not change the source string.

Also this for loop

for (int i = stringcnt-1; arr[i]; i--)

invokes undefined behavior due to the incorrect condition.

The function can be defined the following way as shown in the demonstration program below.

#include <string.h>
#include <stdio.h>
#include <ctype.h>

char * my_strrchr( const char *s, int c )
{
    c = tolower( ( unsigned char )c );

    const char *p = s   strlen( s )   1;

    while (p != s && tolower( ( unsigned char )p[-1] ) != c) --p;

    return p == s ? NULL : ( char * )( p - 1 );
}

int main( void )
{
    char s[] = "helLo";

    char *p = my_strrchr( s, 'l' );

    if (p != NULL)
    {
        printf( "position = %td, substring = %s\n", p - s, p );
    }
}

The program output is

position = 3, substring = Lo
  • Related