strcmp
will not give you the number of characters matching in the given strings. Try the below code, It will give number of matching characters in the input strings.
#include <string.h>
int GetMatchingChars (const char *s1, const char *s2)
{
int len1;
int len2;
int count = 0;
int minLen = 0;
char *shortPtr = NULL;
char *longPtr = NULL;
/* First check if the string are equal, return either len, no need to go further */
if (strcmp (s1, s2) == 0) {
return strlen(s1); /* or s2 */
}
len1 = strlen (s1);
len2 = strlen (s2);
minLen = (len1 <= len2)? len1:len2;
shortPtr = (len1 <= len2)? s1:s2;
longPtr = (shortPtr == s1)? s2:s1;
/* Loop through the shorter string */
while (*shortPtr != '\0') {
if (*shortPtr == *longPtr) {
count++;
}
shortPtr++;
longPtr++;
}
return count;
}
int main()
{
char *s1 = "saac";
char *s2 = "sbab";
printf ("Matching len = %d\n", GetMatchingChars (s1,s2));
}
solved Compare two strings and find mismatch count [closed]