Ionut Goldan
Ionut Goldan

Reputation: 23

How to count the appearances of a string within a string?

I have to count the appearances of a specific C string within a bigger one. I am using strstr() function to count and advance with a char pointer through the big C string. The problem is that it seems to count too little, like the reduction of the text is increasing to fast, jumping over big chunks of characters. I am using a type int variable, called 'x', to 'reduce' text from left to right, but I don't know were is the problem with assigning its new value.

int x=0;
while((p=strstr(text+x,triG))!=NULL)
{
    v[i]++;
    x+=x+3+(p-(text+x));
}

text is of type char*, dynamically alocated. triG is of type char[4], and p is of type char*.

Upvotes: 1

Views: 267

Answers (2)

simonc
simonc

Reputation: 42175

You're increasing the value of x by too much after each match.

int x=0;
while((p=strstr(text+x,triG))!=NULL)
{
    v[i]++;
    x = p - text + strlen(triG);
}

You can also simplify the calculation of x. You were both adding and removing x - these cancel out. Its also a bit more flexible to use strlen(triG) rather than hard-coding the assumption it'll always be 4.

Upvotes: 5

Peter Miehle
Peter Miehle

Reputation: 6070

you have

x+=x+...

you should have either

x = x+...

or

x += ...

Upvotes: 1

Related Questions