Count Words and Characters in a String using C#

Feb 9, 2010 Posted by Lara Kannan
Question is...
Count Words and Characters in a String using C#

A user recently asked me a question on how to use Regular Expressions to count words and characters in a string. Here’s how:

First add a reference to System.Text.RegularExpressions

Here the strOriginal is your string.

// Count words
MatchCollection wordColl =
Regex.Matches(strOriginal, @"[\S]+");

Console.WriteLine(wordColl.Count.ToString());

// Count characters. White space is treated as a character
MatchCollection charColl = Regex.Matches(strOriginal, @".");
Console.WriteLine(charColl.Count.ToString());


Share
Labels: ,

Post a Comment