Thread: Count words in a string

  1. #1
    Registered User
    Join Date
    Oct 2011

    Count words in a string


    I'm looking for a way to count a specific word in a string, here's an example of what I've written

    char TextString[]="hello this is a test string, used used used to count specific words"; 
    char *StringToSearch[3]={"this","a", "used"};
     int this_count=0, a_count=0, used_count=0;
    So I want to put in a loop and look for these words, I was thinking of using strstr function, but that just looks the strings once.

    Do you have a solution?

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Oregon, USA
    Have a moving pointer so you can search the rest of the string after you find a match. Something like:
    char *str, *match;
    int count = 0;
    for(str = TextString;str;str = match == null ? match : match + strlen(StringToSearch[index]))
      if((match = strstr(str, StringToSearch[index])))
    If you understand what you're doing, you're not learning anything.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. count words
    By 74466 in forum C++ Programming
    Replies: 4
    Last Post: 02-17-2006, 09:30 AM
  2. Replies: 7
    Last Post: 01-30-2006, 02:39 AM
  3. words count
    By arlenagha in forum C++ Programming
    Replies: 2
    Last Post: 03-06-2003, 09:29 AM
  4. how to count sentences and words?
    By Ray Thompson in forum C Programming
    Replies: 1
    Last Post: 11-08-2002, 01:42 PM
  5. Replies: 2
    Last Post: 05-05-2002, 01:38 PM

Tags for this Thread