Code:
#include <stdio.h>
#include <string.h>
int smaller_value(int length_word1,int length_word2);
int main (void)
{
char word1[256];
char word2[256];
char prefix[256];
printf("Enter two words: ");
scanf("%s%s",word1,word2);
int length_word1 = strlen(word1);
int length_word2 = strlen(word2);
int j = smaller_value(length_word1,length_word2);
int i;
for (i=0;i<j;i++)
{
if (word1[i] == word2[i])
prefix[i]= word2[i];
}
int length_prefix = strlen(prefix);
if(length_prefix == 0)
printf("%s and %s have no common prefix.",word1,word2);
else
printf("The longest common prefix of %s and %s is %s.", word1, word2, prefix);
printf("\n");
return 0;
}
int smaller_value (int length_word1, int length_word2)
{
if (length_word1 > length_word2)
return length_word2;
if (length_word1 < length_word2)
return length_word1;
if (length_word1 == length_word2)
return length_word1;
}
Objective:
User enters two words, and I find the common prefix, or where the characters from both arrays are the exact same.
Then i print the matching characters into another array
My smaller_value function serves to only compare the characters from the smaller word, since the smaller word would finish comparing first.
So this works:
Enter two words: economy ecology
The longest common prefix of economy and ecology is eco.
However this is the weird output for a different run.
Enter two words: The ehe
The longest common prefix of economy and ecology is $he.
What is the dollar sign doing here?