Thread: Functions in C

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    2
    Rep Power
    0

    Functions in C


    How do i start to write a function that counts the number of times a certain word appears (in standard input)?
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,854
    Rep Power
    481
    Use a finite state machine. See
    http://www.manpagez.com/info/flex/flex-2.5.37/
    or similar document.
    Code:
    %{
      /* flex program, counts occurrences of [Ww]ord in input */
      static int occurrences = 0;
    %}
    
    word [Ww]ord
    
    %%
    
    ^{word}/[[:^alnum:]] ++occurrences;
    [[:^alnum:]]{word}/[[:^alnum:]] ++occurrences;
    .|\n ;
    
    %%
    
    int main() {
      int status = yylex();
      printf("word occurred %d times\n",occurrences);
      return status;
    }
    Last edited by b49P23TIvg; January 20th, 2013 at 03:09 AM. Reason: Insert return
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    187
    Rep Power
    82
    You could use an C++ Standard Template Language (STL) map associative array to solve your problem.

    Check out this wiki.
  6. #4
  7. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,387
    Rep Power
    1871
    "Woodford the wood cutter from Connecticut cut out the deadwood"
    How many times do the words "wood" and "cut" appear in this sentence?

    If this is a newbie question, then scanf() and strcmp() should be all you need.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  8. #5
  9. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,110
    Rep Power
    1803
    Originally Posted by salem
    If this is a newbie question, then scanf() and strcmp() should be all you need.
    "Word : This is a word, another word and a final word."

    "Word" != "word," != "word" != "word."

    Case may need to be considered, as well as non-whitespace delimiters (i.e. punctuation). As a consequence perhaps isalpha() and tolower() also?

IMN logo majestic logo threadwatch logo seochat tools logo