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

后端 未结 6 1556
野性不改
野性不改 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: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.

提交回复
热议问题