joomla visitors
Mithila Software Blog | How to limit string by words in asp.net

How to limit string by words in asp.net

December 27, 2011 Posted by Mithila Software

Limiting words from an asp.net string is basically two step process.


1.Find the total number of words in the string.This is important in the sense that it helps us to compare with the number of words actually required by user.


2.Find the product string by splitting (as a string array) the input string and concatenate it again based on number of words required.

public int CountWords(string s) { int c = 0; for (int i = 1; i < s.Length; i++) { if (char.IsWhiteSpace(s[i - 1]) == true) { if (char.IsLetterOrDigit(s[i]) == true || char.IsPunctuation(s[i])) { c++; } } } if (s.Length > 2) { c++; } return c; } public string LimitWords(string s,int num) { string p = ""; int count = CountWords(s); if (num > count) return s; string[] words = s.Split(); for (int i = 0; i < num; i++) { p += words[i]+" "; } return p; }


How to use the above code ?

 

So , suppose we have a sample string -

string s = "A quick brown fox jumps over the lazy dog" ;

And we now need to limit it to 5 words we can make it happen this way -

string result =  LimitWords(s,5) ;

This will give us an output of "A quick brown fox jumps" , a 5 word string in result variable.

 

blog comments powered by Disqus
Address ::
Mithila Software Solutions,
Green House , 3 GM Road ,
Near Radio Station , Darbhanga
PIN:: 846004
Phone :: # 094-70-625230