Counting words in a string – simple method using C#

Counting words in a string – simple method using C#

C# Code Snippets

Counting words in a string – simple method using C#

public int CountWords(string someText)
{
    // Count the number of words in a text string using C#
    // Simple method - no regex

    int wordCount = 0;

    // change newlines to spaces so we can count words easier
    string plainText = someText.Replace('\n', ' ');

    // get an array of words by splitting chars between spaces
    string[] words = plainText.Split(' ');

    // we can all words, but you may want to filter special chars or little words like 'a'
    for (int i = 0; i < words.Length; i++) { 
        if (words[i].Length > 0) wordCount++;
    }
    return wordCount;
}