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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: