Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,102 questions

55,976 answers

573 users

How to find the starting index of all occurrences of a word in a string in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>

/*
    Find all starting indices of a word inside a larger text.
    This function uses strstr, which returns a pointer to the next
    occurrence of the substring. We loop until no more matches exist.
*/
void find_all_occurrences(const char *text, const char *word)
{
    // If the word is empty, searching is meaningless
    if (word[0] == '\0') {
        return;
    }

    const char *pos = text;   // Start scanning from the beginning
    const char *match = NULL; // Pointer to each found occurrence

    while ((match = strstr(pos, word)) != NULL) {
        /*
            strstr returns a pointer to the first character of the match.
            To convert this pointer into an index, subtract the base pointer.
        */
        size_t index = (size_t)(match - text);
        printf("%zu\n", index);

        /*
            Move forward by one character to continue searching.
            This ensures overlapping matches are also found.
        */
        pos = match + 1;
    }
}

int main(void)
{
    const char *text =
        "the quick brown fox jumps over the lazy dog. the fox is clever.";
    const char *word = "the";

    printf("Text: %s\n", text);
    printf("Word: \"%s\"\n\n", word);
    printf("Occurrences at indices:\n");

    find_all_occurrences(text, word);

    return 0;
}


/*
run:

Text: the quick brown fox jumps over the lazy dog. the fox is clever.
Word: "the"

Occurrences at indices:
0
31
45

*/

 



answered Aug 29 by avibootz

Related questions

...