Velocity Reviews > count the number of occurrences of a substring in a string

# count the number of occurrences of a substring in a string

sibingpeter@gmail.com
Guest
Posts: n/a

 10-01-2005
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

Charles Mills
Guest
Posts: n/a

 10-01-2005

http://www.velocityreviews.com/forums/(E-Mail Removed) wrote:
> 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

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

Barry
Guest
Posts: n/a

 10-01-2005

"Charles Mills" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed) oups.com...
>
> (E-Mail Removed) wrote:
> > 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

>
> 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

sibingpeter@gmail.com
Guest
Posts: n/a

 10-01-2005
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.

Malcolm
Guest
Posts: n/a

 10-02-2005

<(E-Mail Removed)> wrote
>
> "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.