Thursday, October 30, 2014

OCCURENCE FOR C PRO



To Count the Occurence of a Substring in String

#include 
#include 
#include 
char str[100], sub[100];
int count = 0, count1 = 0;
void main()
{
    int i, j, l, l1, l2;
    clrscr();
    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;
        count = 0;
        while ((str[i] == sub[j]))
        {
            count++;
            i++;
            j++;
        }
        if (count == l2)
        {
            count1++;  
            count = 0;
        }
        else
            i++;
    }    
    printf("%s occurs %d times in %s", sub, count1, str);
    getch();
}

Output

Enter a string : prrrogram c prrrogramming
Enter a substring : rr
rr occurs 2 times in prrrogram c prrrogramming


Remove given Word from a String

#include 
#include 
#include 
void main()
{
int i, j = 0, k = 0, count = 0;
char str[100], key[20];
char str1[10][20];
clrscr();
printf("enter string:");
scanf("%[^\n]s",str);
for (i = 0; str[i]!= '\0'; i++)
{
if (str[i]==' ')
{
str1[k][j] = '\0';
k++;
j = 0;
}
else
{
str1[k][j] = str[i];
j++;
}
}
str1[k][j] = '\0';
printf("enter key:");
scanf("%s", key);
for (i = 0;i < k + 1; i++)
{
if (strcmp(str1[i], key) == 0)
{
for (j = i; j < k + 1; j++)
strcpy(str1[j], str1[j + 1]);
k--;
}
}
for (i = 0;i < k + 1; i++)
{
printf("%s ", str1[i]);
}
}
getch();
}


Output

enter string:Welcome to Sanfoundry's C Programming Class, Welcome Again to C class 
enter key:Welcome
to Sanfoundry's C Programming Class, Again to C class


No comments:

Post a Comment