How to count words in a string with C#

4 Answers

0 votes
using System;
using System.Text.RegularExpressions;

class WordCounter
{
    static void Main()
    {
        string s = "C# C Rust Java PHP Python C++";
 
        MatchCollection mc = Regex.Matches(s, @"[\S]+");
 
        Console.WriteLine(mc.Count);
    }
}


/*
run:

7

*/

 



answered Oct 10, 2018 by avibootz
edited Nov 1, 2025 by avibootz
0 votes
using System;

class WordCounter
{
    public static int CountWords(string s) {
        int words = 0;
        
        for (int i = 1; i < s.Length; i++) {
            if (char.IsWhiteSpace(s[i - 1]) == true) {
                if (char.IsLetterOrDigit(s[i]) == true) {
                    words++;
                }
            }
        }
        if (s.Length >= 2) {
            words++;
        }
        
        return words;
    }
        
    static void Main()
    {
        string s = "C# C Rust Java PHP Python C++";
 
        Console.WriteLine(CountWords(s));
    }
}


/*
run:

7

*/

 



answered Oct 10, 2018 by avibootz
edited Nov 1, 2025 by avibootz
0 votes
using System;

class WordCounter
{
    public static int CountWords(string s) {
        
        string [] split_words = s.Split();
 
        int counter = 0;
 
        foreach (string word in split_words) {
             if (word.Trim() != "") {
                counter++;
             }
        }
        
        return counter;
    }
        
    static void Main()
    {
        string s = "C#   (C-Sharp) Programming     Language";
 
        Console.WriteLine(CountWords(s));
    }
}


/*
run:

4

*/

 



answered Nov 1, 2025 by avibootz
0 votes
using System;
 
class WordCounter
{
    public static int CountWords(string s) {
         
        string[] words = s.Split((new Char [] {' ' , '-'})); 
         
        return words.Length;
    }
         
    static void Main()
    {
        string s = "C# is a general-purpose, multi-paradigm programming language";

        Console.WriteLine(CountWords(s));
    }
}
 
 
/*
run:
 
9
 
*/

 



answered Nov 1, 2025 by avibootz
...