C Program to Count Substrings in a String

1. Introduction

Counting occurrences of a substring within a larger string is a commonly encountered problem. In C, this can be achieved using loops and string manipulation functions. This blog post will guide you through creating a program to count occurrences of a substring within a given string.

2. Program Overview

1. Prompt the user to enter the main string.

2. Prompt the user to enter the substring to search for.

3. Use a loop to traverse the main string.

4. For each position in the main string, check if the substring starts from that position.

5. If the substring is found, increment a counter.

6. Display the count after processing the entire string.

3. Code Program

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

int main() {
    char str[100], sub[100];
    int count = 0, len_str, len_sub, i, j;

    // Prompt the user to input the main string
    printf("Enter the main string: ");
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0';  // Remove trailing newline

    // Prompt the user to input the substring
    printf("Enter the substring: ");
    fgets(sub, sizeof(sub), stdin);
    sub[strcspn(sub, "\n")] = '\0';  // Remove trailing newline

    len_str = strlen(str);
    len_sub = strlen(sub);

    for(i = 0; i <= len_str - len_sub; i++) {
        for(j = 0; j < len_sub; j++) {
            if(str[i + j] != sub[j])
        if(j == len_sub) {
            j = 0;

    // Display the result
    printf("The substring '%s' appears %d times in '%s'.\n", sub, count, str);

    return 0;


Enter the main string: appleappleapple
Enter the substring: apple
The substring 'apple' appears 3 times in 'appleappleapple'.

4. Step By Step Explanation

1. We begin by declaring our main string str and our substring sub, as well as the variables we'll need.

2. The user is prompted to input both the main string and the substring.

3. Using two nested for loops, we iterate through each character in the main string and compare it to the characters in the substring.

4. If the substring is found, we increment our count variable by 1.

5. Finally, we print out the number of times the substring was found within the main string.