Sunday, June 18, 2017

Positions of substring in the String

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

char str[100], sub[100];
int count = 0, count1 = 0;
int position[100];

void main()
{
    int i, j, l, l1, l2;

    printf("\nEnter a string : ");
    scanf("%[^\n]s", str);

    l1 = strlen(str);

    printf("\nEnter a substring : ");
    scanf(" %[^\n]s", sub);

    l2 = strlen(sub);

    for (i = 0; i < l1;)
    {
        j = 0;
        int temp = i;
        count = 0;
        while ((str[i] == sub[j]))
        {
            count++;
            i++;
            j++;
        }
        if (count == l2)
        {
            position[count1] = temp;
            count1++;                                  
            count = 0;
            i = temp + 1;
        }
        else
            i = temp + 1;
    }
   
    printf("%s occurs %d times in %s", sub, count1, str);
    int x;
    for(x=0;x< 100;x++)
    {
        if(position[x]==0){
            break;}
       
        printf("\n %d \t", position[x]);
    }
}