How to Compare Last n Characters of A String to Another String in C
If you have a pointer-to-char array, str
, then this:
int len = strlen(str);
const char *last_four = &str[len-4];
will give you a pointer to the last four characters of the string. You can then use strcmp()
. Note that you'll need to cope with the case where (len < 4)
, in which case the above won't be valid.
Just perform if ( strcmp(str1+strlen(str1)-4, str2+strlen(str2)-4) == 0 ) {}
.
Make sure both strings are at least 4 characters long.