Check if String Ends with a Specific Substring in C Language

To check if a string ends with a specific substring, check if substring matches the ending of the string, character by character, in a loop.

C Program

In the following program, we take a string in str and substring in substr, take a for loop to iterate over characters of ending of str and substr until the end of substr, and check if they are same.

Refer C For Loop tutorial.

main.c

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

int main() {
    char str[30] = "apple banana";
    char substr[30] = "na";

    int lenOfStr = strlen(str);
    int lenOfSubstr = strlen(substr);
    
    bool endsWith = false;
    if (lenOfSubstr <= lenOfStr) {
        for (int i = 0; i < lenOfSubstr; i++) {
            if (str[i + lenOfStr - lenOfSubstr] != substr[i]) {
                endsWith = false;
                break;
            }
            endsWith = true;
        }
    }
    
    if (endsWith) {
        printf("String ends with specified substring.\n");
    } else {
        printf("String does not end with specified substring.\n");
    }
    return 0;
}

Output

String does not end with specified substring.
Program ended with exit code: 0
ADVERTISEMENT

Conclusion

In this C Tutorial, we learned how to check if a string ends with a specific substring, with examples.