简体   繁体   中英

How to Compare Last n Characters of A String to Another String in C

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

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.

How about this...

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

char *strrchr(const char *str, int c) - Returns a pointer to the last matching char found in the string, including the NULL char if you so specify. In this case, I use it to get a pointer to the end of the string and then I move the pointer 4 steps back, thus giving a Pointer to the last 4 chars of the string.

I then compare the last 4 chars, to ".avi" and if they match, strcmp returns a 0 or logic FALSE, which I invert in my 'if' condition.

In pure C you can only resort to manual compare:

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;
}

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

Make sure both strings are at least 4 characters long.

Here is a generic function to test:

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;
}
#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM