help with function str cmp

hi, I am trying to recreate the strncmp function without actually using the function from the library I have to come up with the solution.so far i can compare the complete strings but I haven't figured out how to compare only a portion with a given number when the function is called . This is my function it can compare the entire sentences but im not sure about the n value,perhaps i might be missing something?when the function is called in main it is suppose to return 1;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
int ncomparestring (char *S1, char *S2, int n){
    int i=0;

    while(*(S1+i) == *(S2+i) && *(S1+i) != '\0'&&*(S2+i)!='\0'&&(n<i))

            i++;




        if(*(S1+i) < *(S2+i))
        {
            return -1;
        }
        else if(*(S1+i) > *(S2+i))
        {
            return 1;
        }
        else
        {
            return 0;
        }


}

}

1
2
3
4
5
6
7
8
9
10
11
int main()
{ 
    char S1[] = "Happy New Year";
    char S2[] = "Happy Holidays";
 
    
     int answer= ncomparestring(S1,S2,7);
     cout<<answer<<endl;

}
Last edited on
check the value of `i' at line 10
loop look at the conditions of your loop
Last edited on
It would be a lot easier to read this code if you used S1[i] and S2[i] instead of *(S1+i) and *(S2+i).

Going left to right in the condition at line 4, you know that S1[i] == S2[i], so there's no need to check both S1[i] != 0 and S2[i] != 0. Since you know they're equal, you only need to check one.

(n<i) should be (i<n)

After the fix that ne555 mentioned, the return can be simply return S1[i] - S2[i];
Topic archived. No new replies allowed.