How to Count Words in C#: Tutorial for Getting The Number of Words in a String

How to Count Words in C#: Tutorial for Getting The Number of Words in a String
Page content

Counting words

A few weeks ago, I started working on a new web site project, which had one featured news section on the home page. This news feature section was designed to show news title links which then link to a more detailed news page on the site. Under the News title, I wanted to show a short description (or at least 50 to 100 characters) but the problem was I did not want to cut any word off in the middle - this wouldn’t look good for my site visitors. To make sure no words were broken, the code had to know how many words were in the string. Therefore, I decided to create a function that will return number of words rather than number of characters. For anyone who wants to add a word count feature to their web application, here’s what I used.

Code for the Word Count Function

To help you get started using it on your website or application, here is the sample function written in the C# language;

public static string getLimitedWords(string str,int NumberOfWords) {

string[] Words= str.Split(’ ‘);

string _return=string.Empty;

if(Words.Length<=NumberOfWords)

{ _return = str; }

else

{ for(int i=0;i<NumberOfWords;i++)

{ _return+=Words.GetValue(i).ToString()+" “; }

}

return _return.ToString();}

As you can see from this code above, we first take str and split it based on empty spaces. We then move the string into an array Words. Finally, we then use “for loop” to take however number of words we want. For example if the array Words have 10 items, we can pull 0 to 4 items if we want to show first five words from the long string. This can be helpful whenever or wherever we do not want to cut out any words, but do not show a long string.