This is a function that compares two strings to check if they are equal , everything works fine till the point they aren't. I want to calculate difference in value between the first two non-matching characters. Function returns a strange number. The idea is to create a pointer that saves first appeance of not matching character and another one which does the same in the next iteration , then return substraction of them. Basing on what I found on this site and google research I was able to build this so far.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int str_eq(const char *s1,const char *s2)
{
int i = 0;
int d = 0;
char *c ,*cp;
while(*s1 != 0 && *s1 != 0)
{
if(*s1 != *s2)
{
*c = s1[i];
*cp = s2[i + d];
d++;
return ((int)(*cp) - (*c));
}
s1++;
s2++;
i++;
}
return (0);
}
main()
{
const char *s1 = "awerrf";
const char *s2 = "awedre";
if(!(str_eq(s1 , s2)))
{
printf("strings are equal");
}
else
{
printf("strings aren't equal %d" ,str_eq(s1 , s2));
}
}
@edit I've done small update to the function code so the c points to array index where the first non-matching character is spotted , but now how do I go around creating another one that does same with next non-matching character.
int str_eq(const char *s1,const char *s2)
{
int i = 0;
char *c ,*cp;
while(*s1 != 0 && *s2 != 0)
{
if(*s1 != *s2)
{
c = &s1[i];
return (*c);
}
s1++;
s2++;
i++;
}
return (0);
}
expected result (test case)
const char *s1 = "dogydf";
const char *s2 = "dosydg";
s1[0] = s2[0]
s1[1] = s2[1]
s1[2] != s2[2] pointer c = &s1[2];
s1[3] = s2[3]
s1[4] = s2[4]
s1[5] != s2[5] pointer cp = %s1[5] , break loop;
return (*cp) - (*c) //(5 - 2)
@edit_2 The solution (c) RoadRunner.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 2
int str_eq(char *s1, char *s2) {
int indexes[SIZE];
int count = 0, i = 0, j = 0;
while (s1[i] != '\0' && s2[j] != '\0' && count < 2) {
if (s1[i] != s2[j]) {
indexes[count++] = i;
}
i++;
j++;
}
return indexes[1] - indexes[0];
}
int main(void) {
char *s1 = "doedz";
char *s2 = "dogdyy";
printf("Differences = %d\n", str_eq(s1, s2));
return 0;
}