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