String Matched and returning only the count, C Program to count the substring from the main String

         C Program to count the substring from the main String

         

Input 1                  : "AGCVbjasudsfabcaugisabcaabcAA"
Input 2                  : "abc"
Output                   : 3


C Program:

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size

/* Function declaration */
int countOccurrences(char * str, char * toSearch);


int main()
{
    char str[MAX_SIZE];
    char toSearch[MAX_SIZE];
    int count;

    /* Input string and word from user */
    printf("Enter any string: ");
    gets(str);
    printf("Enter word to search occurrences: ");
    gets(toSearch);

    count = countOccurrences(str, toSearch);

    printf("Total occurrences of '%s': %d", toSearch, count);

    return 0;
}


/**
 * Get, total number of occurrences of a word in a string
 */
int countOccurrences(char * str, char * toSearch)
{
    int i, j, found, count;
    int stringLen, searchLen;

    stringLen = strlen(str);      // length of string
    searchLen = strlen(toSearch); // length of word to be searched

    count = 0;

    for(i=0; i <= stringLen-searchLen; i++)
    {
        /* Match word with string */
        found = 1;
        for(j=0; j<searchLen; j++)
        {
            if(str[i + j] != toSearch[j])
            {
                found = 0;
                break;
            }
        }

        if(found == 1)
        {
            count++;
        }
    }

    return count;
}

Comments

Post a Comment

Popular posts from this blog

C Program to Print a trapezium pattern

C Program to Print Pattern 1*2*3*4 9*10*11*12 13*14*15*16 5*6*7*8

Glimpse Of SPYDER | Mahesh Babu | A R Murugadoss | Rakul Preet Singh | Harris Jayaraj | #SPYDER Trailer , Teaser