How to remove stop words from a string in C

1 Answer

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

// A stopwords list is a collection of commonly used words in a language
// that are often removed during text processing tasks. 

// Define stop words
const char* stopWords[] = {
    "i","me","my","myself","we","our","ours","ourselves","you","your",
    "yours","yourself","yourselves","he","him","his","himself","she","her",
    "hers","herself","it","its","itself","they","them","their","theirs",
    "themselves","what","which","who","whom","this","that","these","those",
    "am","is","are","was","were","be","been","being","have","has","had",
    "having","do","does","did","doing","a","an","the","and","but","if","or",
    "because","as","until","while","of","at","by","for","with","about","against",
    "between","into","through","to","from","in","out","on","off","over","further",
    "then","here","there","when","where","why","how","all","any","both","each",
    "few","more","most","other","some","such","no","nor","not","only","own",
    "same","so","than","too","very","can","will","just","don","should","now"
};
int stopWordsCount = sizeof(stopWords) / sizeof(stopWords[0]);

bool isStopWord(const char* word) {
    for (int i = 0; i < stopWordsCount; ++i) {
        if (strcmp(word, stopWords[i]) == 0)
            return true;
    }
    
    return false;
}

void removeStopWords(char* input) {
    char* token = strtok(input, " ");
    char output[1024] = "";

    while (token != NULL) {
        if (!isStopWord(token)) {
            strcat(output, token);
            strcat(output, " ");
        }
        token = strtok(NULL, " ");
    }

    // Trim trailing space
    size_t len = strlen(output);
    if (len > 0 && output[len - 1] == ' ')
        output[len - 1] = '\0';

    printf("%s\n", output);
}

int main() {
    char input[] = "a c programming and java to python a we if c# then a and aa";
    printf("%s\n", input);
    
    removeStopWords(input);
    
    return 0;
}



/*
run:

a c programming and java to python a we if c# then a and aa
c programming java python c# aa

*/

 



answered Jul 17, 2025 by avibootz
...