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");
printf("Enter a sub string \n");

k = strstr(str,rstr);
while (k!= NULL){
        k = strstr(k+1,rstr);
        printf("it occurs %d times \n", i);
return 0;

Recommended Answers

All 4 Replies


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


int *k;

Should be

char *k;

and how can i rearrange this using a for loop

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.

break;//break on some condition

thank you

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.