jQuery and ASP.NET

September 23, 2009

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Count Words and Characters in a String using C# or VB.NET"
 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions