cc-stringsfunction-definitionends-with

having some difficulty with some code around strncmp in C


having some difficulty with some code around strncmp in C just wondering if there is someone that ran into the same problem has me

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int endsWith(char* longStr, char* shortStr);

int main()
{
    char* longString = "Grant is The man";
    char* shortString = "man";
    endsWith(longString,shortString);
    printf("%s\n",shortString);
}

int endsWith(char longStr, char shortStr)
{
    int offset;
    for (offset = 0 ; offset < strlen(shortStr) - strlen(longStr) ; offset ++)
        if (strncmp( longStr , shortStr + offset , strlen(longStr)) == 0)
            return 1;

    return -1;
}

the return should be man and if i inserted is the nothing should be returned or 0.


Solution

  • There are a number of problems with your code.

    With that said, try something more like this instead:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    
    int endsWith(const char* longStr, const char* shortStr);
    
    int main()
    {
        const char* longString = "Grant is The man";
        const char* shortString = "man";
        if (endsWith(longString, shortString))
            printf("Ends with %s\n", shortString);
        else
            printf("Does not end with %s\n", shortString);
    }
    
    int endsWith(const char* longStr, const char* shortStr)
    {
        size_t longLen = strlen(longStr);
        size_t shortLen = strlen(shortStr);
        return (
            (longLen >= shortLen) &&
            (strncmp(longStr + (longLen-shortLen), shortStr, shortLen) == 0)
            ) ? 1 : 0;
    }