Search code examples
cc-stringsstring-comparisonprefixfunction-definition

C: print the longest common prefix


Beginner programmer here, trying to figure out how to find and print the longest common prefix in C.

I have a base here for the program.

#include <stdio.h>

void findprefix(char *str1, char *str2, char *found);

int main(void) {
    char str1[100];
    char str2[100];
    char found[10] = { '\0' }; 
    
    printf("\nGive string 1: ");
    scanf("%99s", str1);
    printf("\nGive string 2: ");
    scanf("%99s", str2);
    
    //Print prefix
    findprefix(str1, str2, found); 
    printf("%s", found);
    
    return 0;
}

//Function to find the longest common prefix
void findprefix(char *str1, char *str2, char *found) {
    
    int i, j;
    
    for () {
        if () {
        }
    }
}

The initial idea is to use a for loop and an if statement in the function but I'm not sure how.


Solution

  • This declaration

    char found[10] = { '\0' }; 
    

    is redundant and does not make a sense.

    Also the function findprefix should return the length of the common prefix.

    The function should be declared and defined the following way

    size_t findprefix( const char *str1, const char *str2 )
    {
        size_t n = 0;
    
        for ( ; *str1 && *str1 == *str2; ++str1, ++str2 )
        {
            ++n;
        }
    
        return n;
    }
    

    And in main you can write

    size_t n = findprefix( str1, str2 );
    
    if ( n != 0 ) printf( "%.*s\n", ( int )n, str1 );
    

    Here is a demonstration progarn.

    #include <stdio.h>
    
    size_t findprefix( const char *str1, const char *str2 )
    {
        size_t n = 0;
    
        for ( ; *str1 && *str1 == *str2; ++str1, ++str2 )
        {
            ++n;
        }
    
        return n;
    }
    
    int main( void ) 
    {
        const char *str1 = "Hello Word!";
        const char *str2 = "Hello Kallum Smith";
        
        size_t n = findprefix( str1, str2 );
    
        if ( n != 0 ) printf( "\"%.*s\"\n", ( int )n, str1 );
        
        return 0;
    }
    

    The program output is

    "Hello "
    

    Using the return value of the function you also can dynamically allocate an array or declare a variable length array where you can copy the prefix if it is required.