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.
There are a number of problems with your code.
your declaration of endsWith()
does not match its definition.
main()
is ignoring the return value of endsWith()
there is no need for a loop in endsWith()
at all. Your approach is implementing an indexOf()
function rather than an endsWith()
function. You can calculate the needed offset
with a single subtraction, no looping required.
But, even if a loop were needed, you are not calculating the loop condition correctly. You are subtracting a larger value from a shorter value, which will result in a negative value. But since strlen()
returns an unsigned type, a negative will wrap to a very large positive value, so you end up looping more than you need.
you are passing the wrong parameters to strncmp()
. Since you want to compare the end of the longStr
to see if it matches the shortStr
, you need to pass longStr + offset
instead of shortStr + offset
, and also pass strlen(shortStr)
instead of strlen(longStr)
.
endsWith()
should return 0
if a match is not found, not -1
.
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;
}