Extension Method: Truncate string

If you’re like me who don’t like to display all the contents of my item’s description (not efficient if length is more than 5000 words) in a full blast on every record that I have on my database, by having the function sitting as an extension method, I can easily call this method to truncate or limit the display of that description to a specified given length and the truncated string will then be replaced by a “…”

Here’s the code of how I create it:

   1: public static class StringEx
   2: {
   3:     /// <summary>
   4:     /// Truncates the string to a specified length and replace the truncated to a ...
   5:     /// </summary>
   6:     /// <param name="text">string that will be truncated</param>
   7:     /// <param name="maxLength">total length of characters to maintain before the truncate happens</param>
   8:     /// <returns>truncated string</returns>
   9:     public static string Truncate(this string text, int maxLength)
  10:     {
  11:         // replaces the truncated string to a ...
  12:         const string suffix = "...";
  13:         string truncatedString = text;
  14:  
  15:         if (maxLength <= 0) return truncatedString;
  16:         int strLength = maxLength - suffix.Length;
  17:  
  18:         if (strLength <= 0) return truncatedString;
  19:  
  20:         if (text == null || text.Length <= maxLength) return truncatedString;
  21:  
  22:         truncatedString = text.Substring(0, strLength);
  23:         truncatedString = truncatedString.TrimEnd();
  24:         truncatedString += suffix;
  25:         return truncatedString;
  26:     }
  27: }

and applying the code above like this:

   1: string newText = "this is the palce i want to be, Cindys is the place to be!";
   2: Console.WriteLine("New Text: {0}", newText.Truncate(40));

I already posted this on Extension Method site.

Extension Method: Get total Word Count of a string

Using regular expression and Extension Method in C#, code below provides a simple way to count all words to a given string excluding all whitespaces, tabs and line breaks.

   1: using System.Text.RegularExpressions;
   2:  
   3: public class MyExtension
   4: {
   5:     /// <summary>
   6:     /// Count all word occurrence
   7:     /// </summary>
   8:     /// <param name="input">string to begin with</param>
   9:     /// <returns>int</returns>
  10:     public static int WordCount(this string input)
  11:     {
  12:         var count = 0;
  13:         try
  14:         {
  15:             // Exclude whitespaces, Tabs and line breaks
  16:             var re = new Regex(@"[^\s]+");
  17:             var matches = re.Matches(input);
  18:             count = matches.Count;
  19:         }
  20:         catch
  21:         {
  22:         }
  23:         return count;
  24:     }
  25: }

and we could use this code like this:

   1: string word = "the quick brown\r\nfox    jumps over the lazy \tdog.";
   2: Console.WriteLine("Total Words: {0}", word.WordCount());
   3: // Output: Total Words: 9

The code is also posted in Extension Method website.

Know more about Regular Expressions.

Technorati Tags:

Extension Method: Check Mobile Number

As a mobile developer for .Net solutions, I often encounter the need to validate the mobile number of a subscriber if it conforms to the correct format. More often, I always create a utility class to do the validation.

One thing I learned from using the latest .NET 3.5 Framework is Extension Method.

So, the way I enable my program to use extension method is as follows:

Method 1:
via the old way:

   1: using System.Text.RegularExpressions;
   2:  
   3: namespace MyConsoleTester
   4: {
   5:     class Utils
   6:     {
   7:         public static bool IsValidMobile(string number)
   8:         {
   9:             bool bFound = false;
  10:             try
  11:             {
  12:                 bFound = Regex.IsMatch(number, @"\A\+\b(639)[012]{1}[0-9]{1}[0-9]{3}[0-9]{4}\b\Z");
  13:             }
  14:             catch (ArgumentException)
  15:             {
  16:  
  17:             }
  18:  
  19:             return bFound;
  20:         }
  21:     }
  22: }

and the implementation would be:

   1: string number = "+639303782321";
   2: bool numValid = Utils.IsValidMobile(number);
   3: Console.WriteLine("Is {0} valid? {1}", number, numValid);

Method 2:
via extension method offers much better and cleaner:

   1: using System.Text.RegularExpressions;
   2:  
   3: namespace MyConsoleTester
   4: {
   5:     public static class SampleExtensions
   6:     {
   7:         public static bool IsValidMobile(this string number)
   8:         {
   9:             bool bFound = false;
  10:             try
  11:             {
  12:                 bFound = Regex.IsMatch(number, @"\A\+\b(639)[012]{1}[0-9]{1}[0-9]{3}[0-9]{4}\b\Z");
  13:             }
  14:             catch (ArgumentException)
  15:             {
  16:                 
  17:             }
  18:  
  19:             return bFound;
  20:         }
  21:     }
  22: }

and the implementation would be as beautiful as this:

   1: using MyConsoleTester;
   2:  
   3: Console.WriteLine("Valid Mobile: +639203782321:\t{0}", "+639303782321".IsValidMobile());

This extension method also posted in ExtensionMethod.net