Function to Count Words in C# (ASP.NET)

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;
}
  • Share/Bookmark

6 Comments

AviralOctober 12th, 2006 at 3:32 pm

Thanks dude.. your code is really good.. solved my problem in a jiffy..

JDecember 2nd, 2006 at 12:53 am

Very useful. Thanks.

WesJuly 3rd, 2007 at 7:04 am

Thanks!!

Swen K.October 21st, 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;
}

NickNovember 24th, 2007 at 6:03 pm

Thanks buddy,

Simple and fast!
Codes like this make the work so smooth!

b2bFebruary 4th, 2009 at 4:29 am

I think the Regex reg = new Regex(”\w+”); is the easiest way here

Leave a comment

Your comment