Check if String starts with a Specific Substring in C Language

To check if a string starts with a specific substring, check if substring matches the starting 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 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 <stdbool.h>

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

    bool startsWith = false;
    for (int i = 0; substr[i] != '\0'; i++) {
        if (str[i] != substr[i]) {
            startsWith = false;
            break;
        }
        startsWith = true;
    }
    
    if (startsWith) {
        printf("String starts with specified substring.\n");
    } else {
        printf("String does not start with specified substring.\n");
    }
    return 0;
}

Output

String starts with specified substring.
Program ended with exit code: 0
ADVERTISEMENT

Conclusion

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