Search code examples
ccharc-stringsfunction-definitionstrchr

Make own strchr() function but case-insensitive


My exercise requires that I can use case-insensitive input. My approch is that I use the tolower and toupper function.

How can I convert the array to lowercase letters?

void KULstrcichr(char *arr, char search)
{
    printf("Return value when uppercase character %c is passed to isupper(): %d\n", search, isupper(search));
    // The  strchr() function returns a pointer to the first occurrence of the character c in the string s.
    if (isupper(search))
    {
        printf("Groß\n");
        char lowercasesearch = tolower(search);
        printf("Das ist der Output: %s", arr);
        char *ptr = strchr(arr, lowercasesearch);
        printf("Das ist der Buchstabe: %s", ptr);
    }
    else
    {
        printf("Klein\n");
        char upercasesearch = toupper(search);
        printf("Das ist der Output: %s", arr);
        char *ptr = strchr(arr, upercasesearch);
        printf("Das ist der Buchstabe: %s", ptr);
    }
}

Solution

  • According to the title of the question

    Make own strchr() function but case-insensitive

    your code does not make any sense. You should write your own function similar to strchr that is declared in the C Standard like

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

    The function should be declared and defined the following way

    char * my_strchr( const char *s, int c )
    {
        c = tolower( ( unsigned char )c );
    
        while ( *s && tolower( ( unsigned char ) *s ) != c ) ++s;
    
        return c == '\0' || *s != '\0' ? ( char * )s : NULL;
    }
    

    Here is a demonstration program.

    #include <stdio.h>
    #include <ctype.h>
    
    char *my_strchr( const char *s, int c )
    {
        c = tolower( ( unsigned char )c );
    
        while (*s && tolower( ( unsigned char )*s ) != c) ++s;
    
        return c == '\0' || *s != '\0' ? ( char * )s : NULL;
    }
    
    int main( void )
    {
        char s[] = "Hello";
        char *p = my_strchr( s, 'h' );
    
        if (p != NULL)
        {
            printf( "position = %td, substring = %s\n", p - s, s );
        }
    }
    

    The program output is

    position = 0, substring = Hello