Wednesday, December 17, 2014

Frequency of Substring in the c



Count Number of Words in a given Text Or Sentence
#include 
#include 
#include 
void main()
{
    char s[200];
    int count = 0, i;
 
    printf("enter the string\n");
    scanf("%[^\n]s", s);
    for (i = 0;s[i] != '\0';i++)
    {
        if (s[i] == ' ')
            count++;    
    }
    printf("number of words in given string are: %d\n", count + 1);
    getch();
}

Output
 
enter the string
welcome to sanfoundry's c-programming class!
number of words in given string are: 5
 
Find the Frequency of Substring in the given String
 
#include 
#include 
#include 
 
 
void main()
{
    int count = 0, i, j = 0, k;
    char str[100], str1[20];
    clrscr();
    printf("Enter the string\n");
    scanf(" %[^\n]s", str);
    printf("Enter the substring to be matched\n");
    scanf(" %[^\n]s", str1);
    k = strlen(str1);
    for (i = 0;str[i] != '\0';)
    {
        if (str[i] == ' ')
        {
            i++;
        }
        else
        {
            if (str[i] == str1[j])
            {
                j++;
                i++;
            }
            else if (j == k)
            {
                j = 0;
                count++;
                i--;
            }
            else
            {
                i++;
                j = 0;
            }
        }
    }
    printf("No of matches of substring in main string is %d\n", count);
getch();
}
 
Output
Enter the string
prrrogram is prrrogramming
Enter the substring to be matched
rr
No of matches of substring in main string is 4

No comments:

Post a Comment