Monday, January 30, 2012

Best Extension Methods: String Extension Methods

Best String Extension Methods

public static class StringExtensions
{
    /// 
    /// if the string is NULL, converts it to string.empty. Helpful when trying to avoid null conditions.
    /// 
    /// 
    /// 
    public static string IsNullThenEmpty(this string inString)
    {
        if (inString == null)
            return string.Empty;
        else
            return inString;
    }			

    public static string[] GetStringInBetween(this string strSource, string strBegin, string strEnd, bool includeBegin, bool includeEnd)
    {

        string[] result = { "", "" };

        int iIndexOfBegin = strSource.IndexOf(strBegin);

        if (iIndexOfBegin != -1)
        {

            // include the Begin string if desired

            if (includeBegin)

                iIndexOfBegin -= strBegin.Length;

            strSource = strSource.Substring(iIndexOfBegin

                + strBegin.Length);

            int iEnd = strSource.IndexOf(strEnd);

            if (iEnd != -1)
            {

                // include the End string if desired

                if (includeEnd)

                    iEnd += strEnd.Length;

                result[0] = strSource.Substring(0, iEnd);

                // advance beyond this segment

                if (iEnd + strEnd.Length < strSource.Length)

                    result[1] = strSource.Substring(iEnd

                        + strEnd.Length);

            }

        }

        else

            // stay where we are

            result[1] = strSource;

        return result;

    }

    public static T ToEnum(this string value)
       where T : struct
    {
       
        //Debug.Assert(!string.IsNullOrEmpty(value));
        return (T)Enum.Parse(typeof(T), value, true);
    }
    public static string Nl2Br(this string s)
    {
        return s.Replace("\r\n", "
").Replace("\n", "
"); } public static string Format(this string format, object arg, params object[] additionalArgs) { if (additionalArgs == null || additionalArgs.Length == 0) { return string.Format(format, arg); } else { return string.Format(format, new object[] { arg }.Concat(additionalArgs).ToArray()); } } public static bool ContainsAny(this string theString, char[] characters) { foreach (char character in characters) { if (theString.Contains(character.ToString())) { return true; } } return false; } /// /// Strip a string of the specified substring. /// /// the string to process /// substring to remove /// /// string s = "abcde"; /// /// s = s.Strip("bcd"); //s becomes 'ae; /// /// public static string Strip(this string s, string subString) { s = s.Replace(subString, ""); return s; } /// /// Strip a string of the specified character. /// /// the string to process /// character to remove from the string /// /// string s = "abcde"; /// /// s = s.Strip('b'); //s becomes 'acde; /// /// public static string Strip(this string s, char character) { s = s.Replace(character.ToString(), ""); return s; } /// /// Strip a string of the specified characters. /// /// the string to process /// list of characters to remove from the string /// /// string s = "abcde"; /// /// s = s.Strip('a', 'd'); //s becomes 'bce; /// /// public static string Strip(this string s, params char[] chars) { foreach (char c in chars) { s = s.Replace(c.ToString(), ""); } return s; } /// /// Splits a string into a NameValueCollection, where each "namevalue" is separated by /// the "OuterSeparator". The parameter "NameValueSeparator" sets the split between Name and Value. /// Example: /// String str = "param1=value1;param2=value2"; /// NameValueCollection nvOut = str.ToNameValueCollection(';', '='); /// /// The result is a NameValueCollection where: /// key[0] is "param1" and value[0] is "value1" /// key[1] is "param2" and value[1] is "value2" /// /// String to process /// Separator for each "NameValue" /// Separator for Name/Value splitting /// public static NameValueCollection ToNameValueCollection(this String str, Char OuterSeparator, Char NameValueSeparator) { NameValueCollection nvText = null; str = str.TrimEnd(OuterSeparator); if (!String.IsNullOrEmpty(str)) { String[] arrStrings = str.TrimEnd(OuterSeparator).Split(OuterSeparator); foreach (String s in arrStrings) { Int32 posSep = s.IndexOf(NameValueSeparator); String name = s.Substring(0, posSep); String value = s.Substring(posSep + 1); if (nvText == null) nvText = new NameValueCollection(); nvText.Add(name, value); } } return nvText; } /// /// Truncates the string to a specified length and replace the truncated to a ... /// /// string that will be truncated /// total length of characters to maintain before the truncate happens /// truncated string public static string Truncate(this string text, int maxLength) { // replaces the truncated string to a ... const string suffix = "..."; string truncatedString = text; if (maxLength <= 0) return truncatedString; int strLength = maxLength - suffix.Length; if (strLength <= 0) return truncatedString; if (text == null || text.Length <= maxLength) return truncatedString; truncatedString = text.Substring(0, strLength); truncatedString = truncatedString.TrimEnd(); truncatedString += suffix; return truncatedString; } /// /// Returns the last few characters of the string with a length /// specified by the given parameter. If the string's length is less than the /// given length the complete string is returned. If length is zero or /// less an empty string is returned /// /// the string to process /// Number of characters to return /// public static string Right(this string s, int length) { length = Math.Max(length, 0); if (s.Length > length) { return s.Substring(s.Length - length, length); } else { return s; } } public static String left(this String s, int len) { return s.Substring(0, Math.Min(len, s.Length)); } public static DateTime ToDateFromDDMMYYYY(this string date) { return DateTime.ParseExact(date, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture); } //Format string to Title case public static string ToTitleCase(this string mText) { if (mText == null) return mText; System.Globalization.CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture; System.Globalization.TextInfo textInfo = cultureInfo.TextInfo; // TextInfo.ToTitleCase only operates on the string if is all lower case, otherwise it returns the string unchanged. return textInfo.ToTitleCase(mText.ToLower()); } /// /// Parses a string into an Enum /// /// The type of the Enum /// String value to parse /// The Enum corresponding to the stringExtensions public static T EnumParse(this string value) { return EnumParse(value, false); } public static T EnumParse(this string value, bool ignorecase) { if (value == null) { throw new ArgumentNullException("value"); } value = value.Trim(); if (value.Length == 0) { throw new ArgumentException("Must specify valid information for parsing in the string.", "value"); } Type t = typeof(T); if (!t.IsEnum) { throw new ArgumentException("Type provided must be an Enum.", "T"); } return (T)Enum.Parse(t, value, ignorecase); } // Enable quick and more natural string.Format calls public static string F(this string s, params object[] args) { return string.Format(s, args); } public static DateTime? ToDateTime(this string source) { if (!string.IsNullOrEmpty(source)) { return Convert.ToDateTime(source); } return null; } public static int? ToNullableInt(this string source) { var i = 0; return int.TryParse(source, out i) ? (int?)i : null; } public static string ToPlural(this string singular) { // Multiple words in the form A of B : Apply the plural to the first word only (A) int index = singular.LastIndexOf(" of "); if (index > 0) return (singular.Substring(0, index)) + singular.Remove(0, index).ToPlural(); // single Word rules //sibilant ending rule if (singular.EndsWith("sh")) return singular + "es"; if (singular.EndsWith("ch")) return singular + "es"; if (singular.EndsWith("us")) return singular + "es"; if (singular.EndsWith("ss")) return singular + "es"; //-ies rule if (singular.EndsWith("y")) return singular.Remove(singular.Length - 1, 1) + "ies"; // -oes rule if (singular.EndsWith("o")) return singular.Remove(singular.Length - 1, 1) + "oes"; // -s suffix rule return singular + "s"; } public static bool IsValidEmailAddress(this string s) { Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"); return regex.IsMatch(s); } /// /// Converts a string into a "SecureString" /// /// Input String /// public static System.Security.SecureString ToSecureString(this String str) { System.Security.SecureString secureString = new System.Security.SecureString(); foreach (Char c in str) secureString.AppendChar(c); return secureString; } public static string ToProperCase(this string text) { System.Globalization.CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture; System.Globalization.TextInfo textInfo = cultureInfo.TextInfo; return textInfo.ToTitleCase(text); } public static bool IsNumeric(this string theValue) { long retNum; return long.TryParse(theValue, System.Globalization.NumberStyles.Integer, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum); } public static bool IsNotNullOrEmpty(this string input) { return !String.IsNullOrEmpty(input); } public static bool IsNullOrEmpty(this string input) { return String.IsNullOrEmpty(input); } public static bool IsNotNullOrEmptyOrSpace(this string input) { if (!String.IsNullOrEmpty(input)) { return !String.IsNullOrEmpty(input.Trim()); } else { return true; } } public static bool IsNullOrEmptyOrSpace(this string input) { if (!String.IsNullOrEmpty(input)) { return String.IsNullOrEmpty(input.Trim()); } else { return true; } } /// /// Count all words in a given string /// /// string to begin with /// int public static int WordCount(this string input) { var count = 0; try { // Exclude whitespaces, Tabs and line breaks var re = new Regex(@"[^\s]+"); var matches = re.Matches(input); count = matches.Count; } catch { } return count; } }

Compiled By: Rajesh Rolen

Share This!


No comments:

Powered By Blogger · Designed By Seo Blogger Templates