C Program to Count Substrings in a String

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.

🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.

▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube

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])
                break;
        }
        if(j == len_sub) {
            count++;
            j = 0;
        }
    }

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

    return 0;
}

Output:

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.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare