1

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

1
  • 1
    Are there any restrictions on the content of text and triG besides the maximum lenght of triG? Do you need to find for example all occurrences of "aaa" in "aaaaaaaaaa"? ;-) Commented Oct 12, 2012 at 9:04

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much...It's seems so silly to me now. To much debugging over C code, I guess. A wish you all a nice day:D
@IonutGoldan Glad this has helped. If you're satisfied with this as an answer, can you consider accepting it?
1

you have

x+=x+...

you should have either

x = x+...

or

x += ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.