How to match the first word after an expression in a string with C

1 Answer

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

void find_next_word(const char *text, const char *expression) {
    char *pos = strstr(text, expression);
    if (pos) {
        pos += strlen(expression); // Move past the found expression
        
        // Skip any spaces
        while (*pos && isspace(*pos)) {
            pos++;
        }

        // Extract the next word
        if (*pos) {
            char word[32] = {0}; // Buffer for the word
            int i = 0;
            while (*pos && !isspace(*pos) && i < sizeof(word) - 1) {
                word[i++] = *pos++;
            }
            word[i] = '\0';
            printf("The first word after '%s' is: %s\n", expression, word);
        } else {
            printf("No word found after '%s'.\n", expression);
        }
    } else {
        printf("No match found!\n");
    }
}

int main() {
    const char *text = "The quick brown fox jumps over the lazy dog.";
    const char *expression = "fox";

    find_next_word(text, expression);
    
    return 0;
}



/*
run:

The first word after 'fox' is: jumps

*/

 



answered Jun 14, 2025 by avibootz
...