Hi All,
Can somebody post me the logic to find all the occurences of a "substring" in a big string.
The function strstr() gives the only first match.
Thanks
Mahesh
Steps 2 and 4 indicate that you'll have to use a loop.
Hi, Thank you for your reply.
This is not so optimized, i feel.
You mean to say,if my main string is 1024 chars long.
I need to loop for 1024 times.
Is there any better way to solve this problem.
Thanks
Mahesh
>You mean to say,if my main string is 1024 chars long.
I need to loop for 1024 times.
No, you'll have to break the loop when strstr() returns NULL, to avoid additional overhead.
To avoid other overhead, you could increase the pointer with the length of the substring you're searching for.
Internally the strstr() function also loops through the string, at the moment when it finds the substring, it stops right there, without looping through the rest of the string, if it hasn't found the substring, the function will have looped through the whole string, and it will return NULL.
When it has found the substring, it will return a pointer to the beginning of that substring.
solution:1
-------------
1)Do like strstr(mainstring,pattern)
2)until return not NULL..
increase pointer by strlen(pattern)
e.g.
"i am going am here"
1st pointer point to beginning of 1st am 'am'
on the 2nd pass change return of strstr pointer by strlen(pattern).
and so on.
solution:2
------------
1)Do strtok(base_str,pattern)
for each iteration...your end of base string will point to staring address of all your patterns.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.