|
|
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?
|
|
|
||
|
|
|
|
Save on Delicious |
|
|
subscribe via rss |
|
subscribe via e-mail |
|
|
print this post |
|
follow me on twitter |





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