/*

 * cmp_prefix.c

 * This program reads two strings and finds their longest common prefix.

 */

 

#include <stdio.h>

#include <string.h>

 

#define MAX_LENGTH 80

 

int main ()

{

  char   found_title[] = "The longest prefix is: ";

  char   not_found_title[] = "No common prefix has been found.";

  char   str1[MAX_LENGTH + 1];      /* The first string. */

  int    len1;                      /* Its length. */

  char   str2[MAX_LENGTH + 1];      /* The second string. */

  int    len2;                      /* Its length. */

  int    l_prefix = 0;              /* Length of the common prefix so far. */

  char   prefix[MAX_LENGTH + 1];

 

  /* Read the first input string and compute its length. */

  printf ("Please enter the first string: ");

  scanf ("%s", str1);

  len1 = strlen (str1);

 

  /* Read the second input string and compute its length. */

  printf ("Please enter the second string: ");

  scanf ("%s", str2);

  len2 = strlen (str2);

 

  /* Find the longest common prefix. */

  while (l_prefix + 1 <= len1 && l_prefix + 1 <= len2 &&

         strncmp (str1, str2, l_prefix + 1) == 0)

  {

    l_prefix++;

  }

 

  /* Print the results. */

  if (l_prefix == 0)

  {

    printf ("%s\n", not_found_title);

  }

  else

  {

    /* Copy the prefix and print it. */

    strncpy (prefix, str1, l_prefix);

    prefix[l_prefix] = '\0';

    printf ("%s%s\n", found_title, prefix);

  }

 

  return (0);

}