Count Words and Characters in a String using C# or VB.NET

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’

C#

// 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());

VB.NET

' Count words
Dim wordColl As MatchCollection = Regex.Matches(strOriginal, "[\S]+")
Console.WriteLine(wordColl.Count.ToString())
' Count characters. White space is treated as a character
Dim charColl As MatchCollection = Regex.Matches(strOriginal, ".")
Console.WriteLine(charColl.Count.ToString())

Here the strOriginal is your string.

I covered some frequently used string operations in my articles on www.dotnetcurry.com over here:

30 Common String Operations in C# and VB.NET – Part I

30 Common String Operations in C# and VB.NET – Part II

No comments:

Post a Comment