count the number of occurrences of a substring in a string

S

sibingpeter

Hi there,

Im trying to find the right way to code the loop to count the number of
occurences of a given substring in a string. Im able to find the first
occurence using the strstr function, but I just cant seem to think of
the right loop that would continue searching after finding this first
occurence. Could someone please help me out here?
 
C

Charles Mills

Hi there,

Im trying to find the right way to code the loop to count the number of
occurences of a given substring in a string. Im able to find the first
occurence using the strstr function, but I just cant seem to think of
the right loop that would continue searching after finding this first
occurence. Could someone please help me out here?

I think this is OK:

int
count_strinstr(const char *big, const char *little)
{
const char *p;
int count = 0;
size_t lil_len = strlen(little);

/* you decide what to do here */
if (lil_len == 0) return -1;

p = strstr(big, little);
while (p) {
count++;
p = strstr(p + lil_len, little);
}
return count;
}

If either arg is NULL this will probably barf.

-Charlie
 
B

Barry

Charles Mills said:
I think this is OK:

int
count_strinstr(const char *big, const char *little)
{
const char *p;
int count = 0;
size_t lil_len = strlen(little);

/* you decide what to do here */
if (lil_len == 0) return -1;

p = strstr(big, little);
while (p) {
count++;
p = strstr(p + lil_len, little);
}
return count;
}

If either arg is NULL this will probably barf.

-Charlie

It depends on whether the occurrences have to be distinctly separate from
one another.
Consider:
little is "abab"
big is "ababababababab"

Barry
 
S

sibingpeter

Hey Charlie,

"p = strstr(p + lil_len, little);"

That addition of the string length was the logic that I was lookin for.
Thanks a lot for your help. Appreciate it.
 
M

Malcolm

"p = strstr(p + lil_len, little);"

That addition of the string length was the logic that I was lookin for.
Thanks a lot for your help. Appreciate it.
If you want to allow sustrings to overlap, add one to the pointer. If you
want to disallow this, add the length of the substring, as Charles showed
you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,241
Latest member
Lisa1997

Latest Threads

Top