SIGN UP MEMBER LOGIN:    
ARTICLE

Counting Words in C#

Posted by Mohammad Waheed Articles | How do I February 14, 2006
This article shows a function that returns number of words rather than number of characters.
Reader Level:

Few weeks ago, I started working on a new web site project, which had one feature news section on the home page. The feature section was designed to show news title link which links to the detail page. Under the news title, I wanted to show description or at least 50 to 100 characters, but the problem was I did not want to cut any word in the middle. Therefore, I decided to create a function that will return number of words rather than number of characters.

Here is the function in C#,

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();
}

Login to add your contents and source code to this article
share this article :
post comment
 

Thank you Sophea :)

Posted by Mohammad Waheed May 25, 2012

I'm Born Sophea. I'm Cambodian. Your Documents is good for me to do Assignment. God bless you.

Posted by Sophea Borns Sep 23, 2011

Yes I totally agree that the StringBuilder is much better.

Thank you
Mohammad

Posted by Mohammad Waheed Feb 05, 2009

Hi,

Isn't it better to use a StringBuilder instead of a string?

Thanks Matt

Posted by Matt Aghnianejad Feb 05, 2009

i was new in this program C# my Team leader wants me to revised the code of generating the customer invoice of our system. the problem was the sequence number didn't moving at all it is fix at only a number. example:1) ad10007/erd 2)ad10007/efd this sample is the problem that i was encountering as of now. i need a code for the sequence numbering example: 1)ad10007/erd 2)ad1008/egd 3)ad1009/ehf this is my problem can you help me? thank you very much sir!!!

Posted by edralyn dulay Jul 24, 2007
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Team Foundation Server Hosting
Become a Sponsor