A 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 links which then link to a more detailed news page. Under the News title, I wanted to show a description (or at least 50 to 100 characters) but the problem was I did not want to cut any word off 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();}
As you can see above, we first take str and split it based on empty spaces. Then move the string into an array Words. 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 5 words from the long string. This is helpful whenever we do not want to cut any words, but do not show a long string.