使用一个strlen(needle),strstr()和测试'\ 0'的通用解决方案:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool endsWith(const char* haystack, const char* needle)
{
bool rv = false;
if (haystack && needle)
{
size_t needle_size = strlen(needle);
if (needle_size == 0) return false;
const char* act = haystack;
while (NULL != (act = strstr(act, needle)))
{
if (*(act + needle_size) == '\0')
{
rv = true;
break;
}
act += 1;
}
}
return rv;
}
int main (int argc, char * argv[])
{
char *a = "file1.gz";
char *b = "1.gz";
char *c = NULL;
char *d = "1.gzabc";
char *e = "1.gzabc1.gz";
char *f = "";
char *g = "rbrbr";
char *h = "rbr";
printf("endsWith:\n");
printf("'%s' '%s' = %d\n",a,b,endsWith(a,b));
printf("'%s' NULL = %d\n",a,endsWith(a,c));
printf("'%s' '%s' = %d\n",d,b,endsWith(d,b));
printf("'%s' '%s' = %d\n",e,b,endsWith(e,b));
printf("'%s' '%s' = %d\n",e,f,endsWith(e,f));
printf("'%s' '%s' = %d\n",g,h,endsWith(g,h));
return 0;
}