23 June 2006
Function to Count Words in C# (ASP.NET)
Posted by Mikhail Esteves under: C#; Tips .
Here’s a C# function to count the number of words in a string:
public static int WordCount (string Text) { string tmpStr;tmpStr = Text.Replace("\t", " ").Trim(); tmpStr = tmpStr.Replace("\n", " "); tmpStr = tmpStr.Replace("\r", " ");while (tmpStr.IndexOf(" ") != -1) tmpStr = tmpStr.Replace(" ", " ");return tmpStr.Split(' ').Length; }
aspnet, csharp, tips, word+count, function 5 Comments so far...
Aviral Says:
12 October 2006 at 3:32 pm.
Thanks dude.. your code is really good.. solved my problem in a jiffy..
J Says:
2 December 2006 at 12:53 am.
Very useful. Thanks.
Wes Says:
3 July 2007 at 7:04 am.
Thanks!!
Swen K. Says:
21 October 2007 at 8:13 pm.
try this:
//using System.Text.RegularExpressions;
public static int WordCount(string txt)
{
int w;
Regex reg = new Regex(”\w+”);
MatchCollection mc = reg.Matches(txt);
if (mc.Count > 0)
w = mc.Count;
else
w = 0;
return w;
}
Nick Says:
24 November 2007 at 6:03 pm.
Thanks buddy,
Simple and fast!
Codes like this make the work so smooth!