arrayscstrchr

How to check if a char is present two times in an array of char in c?


I wanted to check if one char is present in an array of char twice, but strchr() will return the position of the first occurring char.

I was thinking of slicing the array like Python does arr[3:], considered from the 3rd element onward. Does C have such a capability?

if not, what is the best solution for this problem?

Shall I make it myself with for loop, if else, and global variables?


Solution

  • NOTE: This is an answer to revision 1 of the question, which asked how to determine whether a single character occurrs more than once. Meanwhile, the question has been changed to ask how to determine whether any character occurs more than once. I have therefore answered the latest version of the question in a separate answer. EDIT: At the time of this writing, the question has reverted back to revision 1.

    but strchr() will return the position of the first occurring char.

    You can call strchr twice. The second call will find the second character, if it exists. Here is an example:

    #include <stdio.h>
    #include <string.h>
    #include <stdbool.h>
    
    bool does_char_exist_twice( const char *str, char c )
    {
        const char *p;
    
        // try to find first occurrence of character, returning
        // false on failure
        p = strchr( str, c );
        if ( p == NULL )
            return false;
    
        // make p point one past the first occurrence
        p++;
    
        // try to find second occurrence of character
        p = strchr( p, c );
    
        // return true if second occurrence found, otherwise false
        return p != NULL;
    }
    
    void perform_check_and_print_result( const char *str, char c )
    {
        // call the function "does_char_exist_twice" and print the result
        printf(
            "The character '%c' DOES %s exist at least twice in \"%s\".\n",
            c,
            does_char_exist_twice(str, c) ? "   " : "NOT",
            str
        );
    }
    
    int main( void )
    {
        perform_check_and_print_result( "ab"  , 'a');
        perform_check_and_print_result( "aba" , 'a');
        perform_check_and_print_result( "abc" , 'a');
        perform_check_and_print_result( "abca", 'a');
    }
    

    This program prints the following output:

    The character 'a' DOES NOT exist at least twice in "ab".
    The character 'a' DOES     exist at least twice in "aba".
    The character 'a' DOES NOT exist at least twice in "abc".
    The character 'a' DOES     exist at least twice in "abca".