How to remove stop words from a string in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
using System.Linq;

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

class StopwordRemover
{
    private static readonly HashSet<string> stopWords = new HashSet<string>
    {
        "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",
        "so", "than", "too", "very", "can", "will", "just", "don", "should", "now"
    };

    static string RemoveStopWords(List<string> words) {
        return string.Join(" ", words.Where(word => !stopWords.Contains(word)));
    }

    static List<string> SplitWords(string input) {
        return input.Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
    }

    static void Main()
    {
        string input = "a c++ and java to python a we if c# then a and aa";
        Console.WriteLine("Original: " + input);
        
        List<string> words = SplitWords(input);
        
        string filtered = RemoveStopWords(words);
        Console.WriteLine("Filtered: " + filtered);
    }
}



/*
run:

Original: a c++ and java to python a we if c# then a and aa
Filtered: c++ java python c# aa

*/

 



answered Jul 17, 2025 by avibootz

Related questions

...