please guys i need help on the above.
write a finction in c to find the number of times that a given word (i.e a short string) occurs in a sentence.

Dani AI

Generated

A small, practical solution that counts whole-word occurrences (not mere substrings), is case-insensitive, and treats a "word" as a run of alphanumeric characters. This directly addresses 's request (echoed by ) and sidesteps the common pitfall of counting substrings inside larger words. 's pointer to related threads is useful when alternate behaviors (substring matches, regular expressions, Unicode) are required.

#include <stdio.h>
#include <string.h>
#include <ctype.h>

size_t count_word_occurrences(const char *s, const char *word) {
    if (!s || !word) return 0;
    size_t wlen = strlen(word);
    if (wlen == 0) return 0;

    size_t count = 0;
    const char *p = s;
    while (*p) {
        while (*p && !isalnum((unsigned char)*p)) p++;        /* skip separators */
        if (!*p) break;
        const char *start = p;
        size_t len = 0;
        while (*p && isalnum((unsigned char)*p)) { p++; len++; } /* token length */
        if (len == wlen) {
            size_t i;
            for (i = 0; i < wlen; i++) {
                if (tolower((unsigned char)start[i]) != tolower((unsigned char)word[i])) break;
            }
            if (i == wlen) count++;
        }
    }
    return count;
}

/* Example:
   const char *s = "hello hello-world helloworld hello";
   count_word_occurrences(s, "hello")  -> 3
*/

Notes and troubleshooting:

  • The code treats letters and digits as part of words; hyphens/apostrophes split tokens. Change the isalnum test if a different token rule is needed.
  • It performs ASCII case-insensitive comparison via tolower. For true Unicode handling, use a Unicode-aware library.
  • For substring counting (allowing overlaps), iterate with strstr instead of tokenizing.
  • Always cast to unsigned char before passing to ctype.h functions to avoid undefined behavior on negative char values.

Recommended Answers

All 3 Replies

On what above? There is no post above this one! And try reading the RULES as recommended multiple times during your registration here, as well as the post at the top of the forum clearly titled "Read Me: Read This Before Posting". Notice the wording -- before posting.

am so in need to know how the code for the number of times that a give word occurs in a sentence will look like and the final solution of the code,pliz help am so interested to see how this code looks like

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.