Thread: Counting specific word from file

  1. #1
    Registered User
    Join Date
    Mar 2012
    Posts
    5

    Counting specific word from file

    The task that i'm trying to perform is to count the number of times that an specific word is repeated on a .txt file. In this case the word "the".

    My first attempt is:
    Code:
    while(*bufptr++ != '\0'){
        if(strncmp (bufptr,"the",3) == 0){
        i++;
        }}
        printf("The word THE was writen %d times on the file\n",i);
    where bufptr is a pointer to memory: char *bufptr;

    The problem is that with that code it counts not only "the" but also words such as "theater", "lathe". How can i narrow the counting to only count "the" words?.

    Thanks in advance.

  2. #2
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    693
    how about if(strncmp (bufptr,"the ",4) == 0)/? Notice the space after the 'e' in "the".
    Last edited by camel-man; 04-13-2012 at 08:14 PM.

  3. #3
    Registered User
    Join Date
    Mar 2012
    Posts
    5
    Quote Originally Posted by camel-man View Post
    how about if(strncmp (bufptr,"the ",4) == 0)/? Notice the space after the 'e' in "the".
    thanks, with your advice i narrowed to not count words like "theater", then i modified to if(strncmp (bufptr," the ",5) == 0) for "lathe" likes.

  4. #4
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    693
    Only problem you might run into is if the first word of the text file is "The". Then you might be down one count of "the".

  5. #5
    Registered User
    Join Date
    Mar 2012
    Posts
    5
    That's what i've noticed so far, i think that by doing a OR check during the if it can be solved
    Last edited by donaldgx; 04-13-2012 at 08:43 PM.

  6. #6
    Registered User gardhr's Avatar
    Join Date
    Apr 2011
    Posts
    151
    Quote Originally Posted by camel-man View Post
    how about if(strncmp (bufptr,"the ",4) == 0)/? Notice the space after the 'e' in "the".
    No, that's still going to reject a lot of valid strings. Just verify that the very next character isn't alphabetical and everything should work fine.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Searching a specific string/word/etc in a text file?
    By zacharyrs in forum C Programming
    Replies: 5
    Last Post: 11-29-2009, 07:54 PM
  2. Counting the characters from each word from a text file
    By flipguy_ph in forum C Programming
    Replies: 6
    Last Post: 04-27-2009, 05:56 PM
  3. Replies: 2
    Last Post: 12-02-2007, 05:40 AM
  4. strtok - word counting from a file
    By |PiD| in forum C Programming
    Replies: 4
    Last Post: 11-15-2002, 04:16 AM
  5. counting each occurenc of each word in a file
    By ss3x in forum C++ Programming
    Replies: 1
    Last Post: 04-24-2002, 12:18 PM