String Extension Collection for C#

This article brings a small collection of my more commonly used string extensions. For those who don’t know about extension methods, I suggest reading this short article.

Get the initials from a string

public static string ToInitials(this string str)
    {
      return Regex.Replace(str, @"^(?'b'w)w*,s*(?'a'w)w*$|^(?'a'w)w*s*(?'b'w)w*$", "${a}${b}", RegexOptions.Singleline)
    }

Remove line breaks from string

public static string RemoveLineBreaks(this string lines)
{
  return lines.Replace("r", "").Replace("n", "");
}

Replace line breaks in a string

public static string ReplaceLineBreaks(this string lines, string replacement)
{
    return lines.Replace("rn", replacement)
                    .Replace("r", replacement)
                    .Replace("n", replacement);
}

Strip HTML syntax from a string

public static string StripHtml(this string html)
{
   if (string.IsNullOrEmpty(html))
            return string.Empty;
   return Regex.Replace(html, @"<[^>]*>", string.Empty);
}

Pluralise a word

public static string Pluralise(this string value, int count) 
{ 
    if (count <= 1) 
    { 
        return value; 
    } 
    return PluralizationService 
        .CreateService(new CultureInfo("en-US")) 
        .Pluralize(value); 
}

and then

Console.WriteLine( 
    "You have {0} {1} left", player.Lives, "life".Pluralise(player.Lives) 
); 

Get Suffix From Date

    public static string GetDateSuffix(this DateTime date)
    {
        string day = date.Day.ToString();
        if (day.EndsWith("1"))
        {
            return day.StartsWith("1") && date.Day != 1 ? "th" : "st";
        }
        else if (day.EndsWith("2"))
        {
            return day.StartsWith("1") ? "th" : "nd";
        }
        else if (day.EndsWith("3"))
        {
            return day.StartsWith("1") ? "th" : "rd";
        }
        return "th";
    }

Add Working Days to Date

 public static DateTime AddWeekdays(DateTime start, int days)
        {
            int remainder = days % 5;
            int weekendDays = (days / 5) * 2;
            DateTime end = start.AddDays(remainder);

            if (start.DayOfWeek == DayOfWeek.Saturday && days > 0)
            {
                // fix for saturday.          
                end = end.AddDays(-1);
            } if (end.DayOfWeek == DayOfWeek.Saturday && days > 0)
            {
                // add two days for landing on saturday        
                end = end.AddDays(2);
            }
            else if (end.DayOfWeek < start.DayOfWeek)
            {
                // add two days for rounding the weekend      
                end = end.AddDays(2);
            }
            // add the remaining days   
            return end.AddDays(days + weekendDays - remainder);
        }

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.