Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

searching function in C++?

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
I have a text file called stop.txt. How can I count the occcurances of the word "AS" and "as" in it? Also, what if there is something like "christmAS" in the text file? I want it to skip that and only count the word "as" by itself. Thanks
 
Hi,

It is not very difficult.

You must do a little program who open the file in read mode only, read a character (fgetc) and stop when it reach a separator. This allow to identify every word using appropriate separator (like space, \n, \n, etc.). Just make attention to distinguish when you are in a word or outside a word).

I have done a program who open an XML file, search for some particular instruction, and take their values in an array of string.

If you have other questions, just ask.

Best regards,

Michael.

 
main()
{
ifstream input("Stop.txt");

int asCounter = 0;
while(!input.eof() && input.peek()!= EOF)
{
input>>buffer;

if(strlen(buffer) == 2)
{
if(buffer[0] == 'A' || buffer[0] == 'a')
{
if(buffer[0] == 'S' || buffer[0] == 's')
{
asCounter++;
}
}
}
}
That is one way to do it.


A possible other would be using cfiles and CStrings. In that case you would read the whole file in and parse it. I would parse the file from right to left (ie start at the end of the buffer) and base my search on if the current character is an s and the prevoius character checked was a space. then I would set a state and check the next character to the left and see if it is an a and the character before that is a space. THen i would increment the counter and continue the count at the character before the space. ALso reset the state. You may be able to find some examples if you search on "Finite State Machines" on the web.


Matt

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top