C function to compare the last elements of a string with another using pointers

My problem is to see if the str1content ends str2.

I tried this:

int string_ends_with(const char *str1, const char *str2) {
    int len;
    len = strlen(str2);

    while ((*str1 == '\0' - len) && *str1 != '\0') {
        if (strcmp(str1, str2) == 0) {
            return 1;
        } else {
            return 0;
        }
    }
}

int main() {
    char str[10] = "banana";
    char str1[5] = "ana";

    string_ends_with(str, str1);

    return 0;
}

What am I doing wrong?

This problem should be solved only with pointers.

+4
source share
3 answers

This condition is in the while statement.

while((*str1 == '\0' - len) && *str1 != '\0')

doesn't make sense. What does it mean '\0' - len?

You can write a function as follows

int string_ends_with(const char *str1, const char *str2)
{
    size_t n1 = strlen( str1 );
    size_t n2 = strlen( str2 );

    return n2 <= n1 && strcmp( str1 + n1 - n2, str2 ) == 0;
}

If you cannot use standard functions, you can write a function as follows

int string_ends_with(const char *str1, const char *str2)
{
    const char *p1 = str1;
    const char *p2 = str2;

    while ( *p1 ) ++p1;
    while ( *p2 ) ++p2;

    while ( p1 != str1 && p2 != str2 && *p1 == *p2 ) --p1, --p2;

    return  p2 == str2 && *p1 == *p2;
}
+5
source

This will be useful if you want to know which row has a larger / smaller value.

int string_ends_with(char *p1, char *p2)
{
    char    *q1;
    char    *q2;

    if (! p1 || ! p2)
        return something;

    (p1 + (strlen(p1) - 1));
    (p2 + (strlen(p2) - 1));

    while (q1 >= p1 && q2 >= p2) {
       if (*q2 < *q1) return -1;
       else if (*q2 > *q1) return 1;

       q1--; q2--;
    }

    return 0;
}

EDIT: , , , . , .

.

0

The original test is incorrect, as indicated in other answers.

Here is a slightly smaller and potentially more efficient version:

int string_ends_with(const char *str1, const char *str2) {
    const char *p1 = str1;
    const char *p2 = str2;

    while (*p1) p1++;  // same as p1 += strlen(p1);
    while (*p2) p2++;  // same as p2 += strlen(p2);

    while (p2 != str2) {
        if (p1 == str1 || *--p1 != *--p2)
            return 0;
    }
    return 1;
}

Note that your test function mainshould output something and do more tests:

void test(const char *a, const char *b) {
    printf("\"%s\" ends with \"%s\": %s\n", 
           a, b, string_ends_with(a, b) ? "yes" : "no");
}

int main(void) {
    char str[] = "banana";
    char str1[] = "ana";

    test(str, str1);
    test(str1, str);
    test(str, str);
    test(str, "");
    test("", str);
    test("", "");

    return 0;
}
0
source

Source: https://habr.com/ru/post/1625756/


All Articles