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

后端 未结 6 1521
野性不改
野性不改 2021-01-02 07:41

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

相关标签:
6条回答
  • 2021-01-02 08:16

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

    Make sure both strings are at least 4 characters long.

    0 讨论(0)
  • 2021-01-02 08:17
    #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 讨论(0)
  • 2021-01-02 08:19

    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.

    0 讨论(0)
  • 2021-01-02 08:22

    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;
    }
    
    0 讨论(0)
  • 2021-01-02 08:31

    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.

    0 讨论(0)
  • 2021-01-02 08:34

    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;
    }
    
    0 讨论(0)
提交回复
热议问题