0

I want to write a program to count the number of occurances of a substring in a main string. am having trouble with this please i need help. my code is below, you can show be a better way to write it and tell me were i went wrong. am new to this

#include <stdio.h>
#include <string.h>
int main()
{
char str[100], rstr[100];
int i =0,*k;
printf("Enter a string \n");
gets(str);
printf("Enter a sub string \n");
gets(rstr);

k = strstr(str,rstr);
while (k!= NULL){
        i++;
        k = strstr(k+1,rstr);
        }
        printf("it occurs %d times \n", i);
return 0;
}
2
Contributors
4
Replies
6
Views
6 Years
Discussion Span
Last Post by cesione
0

Hint.

Don't use gets its a dangerous function. Instead use fgets().
Don't use magic numbers like 100 use a macro like

#define ARR_SIZE 100

Also

int *k;

Should be

char *k;

Edited by gerard4143: n/a

0

and how can i rearrange this using a for loop

Why would you use a for loop? The purpose of a for loop is to iterate over a collection of data a fixed number of times...If you want a for loop to behave like a while loop then try this.

for(;;)
{
break;//break on some condition
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.