How to compare last n characters of a string with another string in C

Imagine I have two lines, one of them is the URL / sdcard / test.avi, and the other is "/sdcard/test.mkv". I want to write an if statement that looks to see if the last four characters of the string are ".avi" or not in C. How can I do this? Using strcmp or what and how?

+5
source share
6 answers

If you have an array of char pointers str, then this:

int len = strlen(str);
const char *last_four = &str[len-4];

. strcmp(). , , (len < 4), .

+21

C :

int endswith(const char* withwhat, const char* what)
{
    int l1 = strlen(withwhat);
    int l2 = strlen(what);
    if (l1 > l2)
        return 0;

    return strcmp(withwhat, what + (l2 - l1)) == 0;
}
+1

if ( strcmp(str1+strlen(str1)-4, str2+strlen(str2)-4) == 0 ) {}.

, 4 .

+1

:

int EndsWithTail(char *url, char* tail)
{
    if (strlen(tail) > strlen(url))
        return 0;

    int len = strlen(url);

    if (strcmp(&url[len-strlen(tail)],tail) == 0)
        return 1;
    return 0;
}
0
#include <dirent.h>
#include <string.h>

int main(void)
{
    DIR *dir;
    struct dirent *ent;
    char files[100][500];
    int i = 0;

    memset(files, 0, 100*500);
    dir = opendir ("/sdcard/");
    if (dir != NULL)
    {
        /* Print all the files and directories within directory */
        while ((ent = readdir (dir)) != NULL)
        {
            strcpy(files[i], ent->d_name);
            if(strstr(files[i], ".avi") != NULL)
            {
                printf("\n files[%d] : %s is valid app file\n", i, files[i]);
                i++;
            }
        }
        closedir (dir);
    }
    return 0;
}
0

...

if (!strcmp(strrchr(str, '\0') - 4, ".avi")){
    //The String ends with ".avi"
}

char *strrchr(const char *str, int c) - char , NULL char, . , 4 , 4 .

Then I compare the last 4 characters with ".avi", and if they match, strcmp returns 0 or boolean FALSE, which I invert in my "if" state.

0
source

All Articles