Searching problem
Hey guys, I am using the code below ot search for words in a text file and count them. I now would like to do something a little more advanced for example if a text file contains
"hello my name is kim" I want to be able to increment a variable everytime the words hello and my appear next to eachother, is there an easy way to do this?
Thanks.
char array [200];
ifstream file;
while (file >> array)
{
if(strstr(array,"test") != 0)
test++;
}
Jon182
Junior Poster in Training
91 posts since Jul 2005
Reputation Points: 10
Solved Threads: 0
Can you not use strstr to look for "hello my"? Or are you looking for any combination such as "my hello", hellomy", and so forth? In that case, the easiest way would be to use a regular expression, which C doesn't support as a standard library. You would need to write your own manually or use a third-party library. Alternatively, you can just hardcode a test for every possible combination. Your choice.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Hi thanks for your quick reply I would hardcode each, but i'm not sure what you mean by a regular expression, what is that?
Thanks for your reply.
Jon182
Junior Poster in Training
91 posts since Jul 2005
Reputation Points: 10
Solved Threads: 0
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Thanks, sorry i'm not very good at c++ how would I go about coding that? Could i use my array and the code I have posted above?
Jon182
Junior Poster in Training
91 posts since Jul 2005
Reputation Points: 10
Solved Threads: 0
>Thanks, sorry i'm not very good at c++
This has nothing to do with C++ since you've shown that you can do a simple string search. At this point it's a problem solving issue. I personally don't think it's terribly difficult to do this:
if ( strstr ( array, "hello my" ) != NULL )
++test;
if ( strstr ( array, "hellomy" ) != NULL )
++test;
etc...
And since you're probably new to programming, it's unlikely that you'll have an easy time working with regular expressions.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Thanks again for you help, I am just wondering how come its !=NULL rather than !=0?
The code also doesn't seem to be working for me is it because I am reading the file in one word at a time?
Jon182
Junior Poster in Training
91 posts since Jul 2005
Reputation Points: 10
Solved Threads: 0
>I am just wondering how come its !=NULL rather than !=0?
Both are the same. NULL simply clarifies your intentions of using 0 in a pointer context. But if you use it, be sure to include a header that defines it. In C++ you'll probably want for NULL unless you use other C libraries.
>it because I am reading the file in one word at a time?
Yes. Use getline to read an entire line and it should work better.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401