C# : String utility code snippets

Below are the common utilities / code snippets often required while working with strings. I have written them as static functions.  [C# 3.0]

StripHtml

C# function to strip Html tags / markups from input string. Rather, it not only strips Html tags but any sort of markups written in <xxx> format. Reference to System.Text.RegularExpressions namespace needed.

   1: /// <summary>
   2: /// Removes HTML tags / markups from original string and returns it
   3: /// </summary>
   4: /// <param name="original"></param>
   5: /// <returns></returns>
   6: public static string StripHtml(string original)
   7:  {
   8:     return Regex.Replace(original, @"<(.|\n)*?>", string.Empty);
   9:  }

Removes extra spaces

Below code removes all extra spaces (wherever there is more then one space)

   1: public static string RemoveExtraSpaces(string original)
   2: {
   3:    while (original.IndexOf("  ") > 0)
   4:    {
   5:         original = original.Replace("  ", " ");
   6:    }
   7:    return original;
   8: }

Valid Email ID & URL check

Below are the C# functions to check if input string is valid email id or a valid URL. Reference to System.Text.RegularExpressions namespace needed.

   1: public static bool IsValidEMailID(string email)
   2: {
   3:      return Regex.IsMatch(email, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
   4: }
   5:  
   6:         
   7: public static bool IsValidUrl(string url)
   8: {
   9:    return Regex.IsMatch(url, @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?");
  10: }

If Null Then Empty

   1: public static string IfNullThenEmpty(string inStr)
   2:        {
   3:            return inStr ?? string.Empty;
   4:        }

0 comments

Popular Posts

 
© Old - Pinal Bhatt's Blog
From the desk of Pinal Bhatt | www.PBDesk.com
Back to top