How to check whether a string ends with another string in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>

int string_ends_with(const char *s, const char *ending) {
    if (!s || !ending)
        return 0;
    size_t lens = strlen(s);
    size_t lene = strlen(ending);
    if (lene >  lens)
        return 0;
    return strncmp(s + lens - lene, ending, lene) == 0;
}

 
int main() {
    char s[] = "file.txt";
	
	if (string_ends_with(s, ".txt"))        
        puts("yes");
    else
        puts("no");
		
    return 0;
}


  
/*
run:
  
yes
  
*/

 



answered Nov 15, 2019 by avibootz

Related questions

3 answers 212 views
3 answers 245 views
1 answer 162 views
1 answer 139 views
3 answers 177 views
1 answer 134 views
...