Thursday 30 June 2011

C# - String Helpers - Various

Usage


Various short and fairly self-explanatory string helpers.

Snippets


using System;
using System.Drawing;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;


namespace My.Helpers
{
    public class StringHelpers
    {
        public static int Count(string text, string pattern)
        {
            // Count how many occurrences of 'pattern' there are in 'text'.
            int result = 0;

            try
            {
                int start = 0;

                while (true)
                {
                    int index = text.IndexOf(pattern, start);
                    if (index < 0) break;

                    result++;
                    start = index + pattern.Length;
                }
            }
            catch (System.Exception Ex)
            {
                Log.WriteException("StringHelpers", "Count", Ex);
            }

            return result;
        }

        public static string Get(string text, string defaultValue)
        {
            if (!String.IsNullOrWhiteSpace(text))
                return text;
            else
                return defaultValue;
        }

        public static string GetFirstLine(string text)
        {
            string result = "";

            if (!String.IsNullOrWhiteSpace(text))
            {
                int index = text.IndexOf(Environment.NewLine);

                if (index < 0)
                    result = text;
                else
                    result = text.Substring(0, index);
            }

            return result;
        }

        public static string GetMD5Hash(string text)
        {
            var x = new MD5CryptoServiceProvider();
            byte[] bs = Encoding.UTF8.GetBytes(text);

            // Compute the MD5 hash value.
            bs = x.ComputeHash(bs);

            // Convert it to a hex string.
            var s = new System.Text.StringBuilder();

            foreach (byte b in bs)
                s.Append(b.ToString("x2").ToLower());

            return s.ToString();
        }

        public static string RegexExtract(string text, string pattern)
        {
            // Return the first part of 'text' that matches 'pattern' (if any), otherwise an empty string.
            try
            {
                Regex rx = new Regex(pattern);
                Match match = rx.Match(text);

                if (match.Success)
                    return match.Value;
            }
            catch (System.Exception Ex)
            {
                Log.WriteException("ServiceTester", "RegexMatch", Ex);
            }

            return "";
        }

        public static bool RegexMatch(string text, string pattern)
        {
            // Does 'text' match 'pattern'?
            try
            {
                Regex rx = new Regex(pattern);      // , RegexOptions.Compiled | RegexOptions.IgnoreCase);
                return rx.IsMatch(text);
            }
            catch (Exception Ex)
            {
                Log.WriteException("ServiceTester", "RegexMatch", Ex);
            }

            return false;
        }

        public static string Repeat(char ch, int count)
        {
            return new String(ch, count);
        }

        public static string Repeat(string text, int count)
        {
            var builder = new StringBuilder();

            for (int i = 0; i < count; i++)
                builder.Append(text);

            return builder.ToString();
        }

        public static string Tabify(string text, int tabWidth)
        {
            // Replaces each sequence of 'tabWidth' spaces with a tab.
            // Ignores smaller numbers of spaces (similar to VS2010).
            if (String.IsNullOrWhiteSpace(text))
                return "";

            string spaces = new String(' ', tabWidth);

            return text.Replace(spaces, "\t");
        }

        public static string Untabify(string text, int tabWidth)
        {
            if (String.IsNullOrWhiteSpace(text))
                return "";

            string spaces = new String(' ', tabWidth);

            return text.Replace("\t", spaces);
        }
    }
}

No comments:

Post a Comment