Useful String Functions in C#

Not much verbiage necessary to introduce a code file I'll paste below. It's all about string manipulation. There are useful string functions in VB, and I have mimicked/extended some of these.

The file includes string conversion functions, some data type identification functions, some string edit functions, and some string locater functions. All methods in the class are static (one can call them without object instantiation).

My favorites:

GetEachFieldValue:        
Easily grabs a list by parsing with any characters the developer chooses

GetExactPartOfString: 
Extricates a portion of a full stream of characters, based on a left and right bound character of the developer's choice

GetFileNameFromPath:  
Returns just the filename, from inside a full path. Developer can choose whether to include the extension, or not.

Clean:                
Purges a string of any characters the developer wishes to remove. There is an exceptions argument that allows fine-tuning.

 

/*
 * Author: aendenne
 * Email: AutomateAnything@yahoo.com
 * Create Date: April 21, 2007
 * Last Modified Date: August 14, 2007
 * Version: 2.1
 */ 


using
System;
using System.Collections.Generic; 

namespace
YourNamespace.Tools
{
    /// <summary>
    /// Static class that exposes many string methods,
   
/// useful for string evaluation and edits
    /// </summary>
    public static class StringTool
    {

        #region StringConstantsToHelpWithComparisons
        private const string m_Letters = "abcdefghijklmnopqrstuvwxyz";
        private const string m_Digits = "0123456789";
        private const string m_ForwardSlash = "/";
        private const string m_BackSlash = "\\";
        private const string m_Period = ".";
        private const string m_DollarSign = "$";
        private const string m_PercentSign = "%";
        private const string m_Comma = ",";
        private const string m_Yes = "yes";
        private const string m_No = "no";
        private const string m_True = "true";
        private const string m_False = "false";
        private const string m_1 = "1";
        private const string m_0 = "0";
        private const string m_y = "y";
        private const string m_n = "n";

        #endregion 

        #region DataTypeStringConstants
        public const string m_GUID = "guid";
        public const string m_Boolean1 = "boolean";
        public const string m_Boolean2 = "bool";
        public const string m_Byte = "byte";
        public const string m_Char = "char";
        public const string m_DateTime = "datetime";
        public const string m_DBNull = "dbnull";
        public const string m_Decimal = "decimal";
        public const string m_Double = "double";
        public const string m_Empty = "empty";
        public const string m_Int16_1 = "int16";
        public const string m_Int16_2 = "short";
        public const string m_Int32_1 = "int32";
        public const string m_Int32_2 = "int";
        public const string m_Int32_3 = "integer";
        public const string m_Int64_1 = "int64";
        public const string m_Int64_2 = "long";
        public const string m_Object = "object";
        public const string m_SByte = "sbyte";
        public const string m_Single = "single";
        public const string m_String = "string";
        public const string m_UInt16 = "uint16";
        public const string m_UInt32 = "uint32";
        public const string m_UInt64 = "uint64";

        #endregion 

        #region MethodsThatCheckDataType
        /// <summary>
        /// Evaluates whether passed-in string can be converted to a bool
        /// </summary>
        /// <param name="stream">string to check</param>
        /// <returns>
        /// bool indicating whether stream is a bool (0, 1, true/True,
        /// false/False)
        /// </returns>
        public static bool IsStandardBool(string stream)
        {
            try
            {
                if (stream == null || stream == string.Empty)
                    return false; 
                stream = stream.Trim().ToLower();
                switch (stream)
                {
                    case m_0:
                        return true;
                    case m_1:
                        return true;
                    case m_True:
                        return true;
                    case m_False:
                        return true;
                    default:
                        return false;
                }
            }
            catch (Exception ex)
            {
                //ErrorTool.ProcessError(ex);
                return false;
            }
        } 

        /// <summary>
        /// Evaluates whether string can can be COERCED to a bool
        /// </summary>
        /// <param name="stream">string to check</param>
        /// <returns>
        /// bool indicating whether argument is a standard or custom bool
        /// (0, 1, true/True, false/False) OR (y/Y, yes/Yes, n/N, no/NO)
        /// </returns>
        public static bool IsFriendlyBool(string stream)
        {
            try
            {
                if (stream == null || stream == string.Empty)
                    return false; 
                stream = stream.Trim().ToLower();
                switch (stream)
                {
                    case m_0:
                        return true;
                    case m_1:
                        return true;
                    case m_True:
                        return true;
                    case m_False:
                        return true;
                    case m_n:
                        return true;
                    case m_y:
                        return true;
                    case m_No:
                        return true;
                    case m_Yes:
                        return true;
                    default:
                        return false;
                }
            }
            catch (Exception ex)
            {
               
//ErrorTool.ProcessError(ex);
                return false;
            }
        }

        /// <summary>
        /// Returns a bool conversion of the passed in string
        /// </summary>
        /// <param name="stream">string to convert/coerce</param>
        /// <returns>
        /// bool representation of passed-in string
        /// </returns>
        public static bool CoerceToBool(string stream)
        {
            try
            {
                stream = stream.Trim().ToLower();
                switch (stream)
                {
                    case m_0:
                        return true;
                    case m_1:
                        return true;
                    case m_True:
                        return true;
                    case m_False:
                        return false;
                    case m_n:
                        return false;
                    case m_y:
                        return true;
                    case m_No:
                        return false;
                    case m_Yes:
                        return true;
                    default:
                        return false;
                }
            }
            catch (Exception ex)
            {
                //ErrorTool.ProcessError(ex);
                return false;
            }
        } 

        /// <summary>
        /// Evaluates whether passed-in string contains any characters/
       
/// digits/symbols. Trims spaces before checking.
        /// </summary>
        /// <param name="stream">string to check</param>
        /// <returns>
        /// bool indicating whether argument is void of characters/
        ///
digits/symbols
        ///</returns>
        public static bool IsEmpty(string stream)
        {
            try
            {
                if (stream == null || stream == string.Empty
                    || stream.Trim() == string.Empty)
                    return true;
                else
                    return false;
            }
            catch (Exception ex)
            {
               
//ErrorTool.ProcessError(ex);
                return false;
            }
        } 

        /// <summary>
        /// Checks each character of the string for any character other
        ///
than a digit, or a dollar sign or a percentage sign. If any
        ///
are found, returns false indicating that the stream is NOT
        ///
a number
        /// </summary>
        /// <param name="stream">
        /// The stream of characters (string) to check
        /// </param>
        /// <returns>
        /// True/False value indicating whether the string can be
       
/// coerced to a number
        /// </returns>
        public static bool IsNumber(string stream)
        {
            try
            {
                if (stream == null || stream == string.Empty)
                    return false; 
      
                string character = string.Empty;
                //set a string up of all characters that may indicate
                //that the stream is a number, or a formatted number:
                string validCharacters = m_Digits + m_Period +
                    m_DollarSign + m_Comma; 
                for (int i = 0; i < stream.Length; i++)
                {
                    character = stream.Substring(i, 1);
                    if (!validCharacters.Contains(character))
                        return false;
                }
                return true;
            }
            catch (Exception ex)
            {
               
//ErrorTool.ProcessError(ex);
                return false;
            }
        } 

        /// <summary>
        /// Checks the string to see whether it is a number & if it is,
        /// then it checks whether there is formatting applied to that #
        /// </summary>
        /// <param name="stream">
        /// The stream of characters (string) to check
        /// </param>
        /// <returns>
        /// True/False value indicating whether the string is a number
        /// that is formatted (contains digits and number formatting)
        /// </returns>
        public static bool IsFormattedNumber(string stream)
        {
            try
            {
                if (stream == null || stream == string.Empty)
                    return false;

                string character = string.Empty;
                //set a string up of all characters that may indicate that
                //the stream is a number, or a formatted number:
                string validCharacters = m_Digits + m_Period +
                    m_DollarSign + m_PercentSign + m_Comma; 

                for (int i = 0; i < stream.Length; i++)
                {
                    character = stream.Substring(i, 1);
                    if (!validCharacters.Contains(character))
                        //the stream contains non-numeric characters:
                        return false;
                }
                //at this point, each single character is a number OR an
                //
allowable symbol, but we must see whether those
                //
characters contain a formatting character:
                string formattingCharacters = m_DollarSign +
                    m_PercentSign + m_Comma;
                for (int i = 0; i < stream.Length; i++)
                {
                    if (formattingCharacters.Contains(character))
                        return true;
                }
                //still here? then the stream is a number, but NOT a
                //formatted number

                return false;
            }
            catch (Exception ex)
            {
               
//ErrorTool.ProcessError(ex);
                return false;
            }
        } 

        /// <summary>
        /// Checks whether string can be coerced into a DateTime value
        /// </summary>
        /// <param name="stream">The string to check/// </param>
        /// <returns>
        /// bool indicating whether stream can be converted to a date
        /// </returns>
        public static bool IsDate(string stream)
        {
            try
            {
                if (stream == null || stream == string.Empty)
                    return false; 
                DateTime checkDate = new DateTime();
                bool dateType = true;
                try
                {
                    checkDate = DateTime.Parse(stream);
                }
                catch
                {
                    dateType = false;
                }
                return dateType;
            }
            catch (Exception ex)
            {
               
//ErrorTool.ProcessError(ex);
                return false;
            }
        }  

        /// <summary>
        /// Checks the string to see whether it is a number and if it is,
        /// then it checks whether there is a decimal in that number.
        /// </summary>
        /// <param name="stream">
        /// The stream of characters (string) to check
        /// </param>
        /// <returns>
        /// True/False value indicating whether the string is a
        /// double---must be a number, and include a decimal
        /// in order to pass the test
        /// </returns>
        public static bool IsDouble(string stream)
        {
            try
            {
                if (stream == null || stream == string.Empty)
                    return false; 

                if (!IsNumber(stream))
                    return false; 

                //at this point each character is a number OR an allowable
                //symbol; we must see whether the string holds the decimal:
                if (stream.Contains(m_Period))
                    return true; 

                //still here? the stream is a #, but does NOT have a decimal
                return false;
            }
            catch (Exception ex)
            {
              
//ErrorTool.ProcessError(ex);
                return false;
            }
        } 

        /// <summary>
        /// Checks string to see if it matches a TypeCode string and returns
        /// that TypeCode, or returns TypeCode.Empty if there is no match
        /// </summary>
        /// <param name="dataTypeString">
        /// String representation of a TypeCode (string, int, bool...)
        /// </param>
        /// <returns>TypeCode that maps to the dataTypeString</returns>
        public static TypeCode GetDataType(string dataTypeString)
        {
            try
            {
                switch (dataTypeString.ToLower())
                {
                    // todo: isn't there a better way for guid?
                    case m_GUID:
                        return TypeCode.Object;
                    case m_Boolean1:
                        return TypeCode.Boolean;
                    case m_Boolean2:
                        return TypeCode.Boolean;
                    case m_Byte:
                        return TypeCode.Byte;
                    case m_Char:
                        return TypeCode.Char;
                    case m_DateTime:
                        return TypeCode.DateTime;
                    case m_DBNull:
                        return TypeCode.DBNull;
                    case m_Decimal:
                        return TypeCode.Decimal;
                    case m_Double:
                        return TypeCode.Double;
                    case m_Empty:
                        return TypeCode.Empty;
                    case m_Int16_1:
                        return TypeCode.Int16;
                    case m_Int16_2:
                        return TypeCode.Int16;
                    case m_Int32_1:
                        return TypeCode.Int32;
                    case m_Int32_2:
                        return TypeCode.Int32;
                    case m_Int32_3:
                        return TypeCode.Int32;
                    case m_Int64_1:
                        return TypeCode.Int64;
                    case m_Int64_2:
                        return TypeCode.Int64;
                    case m_Object:
                        return TypeCode.Object;
                    case m_SByte:
                        return TypeCode.SByte;
                    case m_Single:
                        return TypeCode.Single;
                    case m_String:
                        return TypeCode.String;
                    case m_UInt16:
                        return TypeCode.UInt16;
                    case m_UInt32:
                        return TypeCode.UInt32;
                    case m_UInt64:
                        return TypeCode.UInt64;
                    default:
                        return TypeCode.Empty;
                }
            }
            catch (Exception ex)
            {
              
//ErrorTool.ProcessError(ex);
                return TypeCode.Empty;
            }
        }

        #endregion

        #region StringConversions
        /// <summary>
        /// Returns a date, as coerced from the string argument. Will raise
        /// an error, if the string cannot be coerced
        /// ----so, use IsDate in this same class FIRST
        /// </summary>
        /// <param name="stream">string to get date value from</param>
        /// <returns>a DateTime object</returns>
        public static DateTime GetDate(string stream)
        {
            DateTime dateValue = new DateTime(); 
            try
            {
                dateValue = DateTime.Parse(stream);
                return dateValue;
            }
            catch (Exception ex)
            {
              
//ErrorTool.ProcessError(ex);
                return dateValue;
            }
        } 

        /// <summary>
        /// Returns an int, as coerced from the string argument.
        /// Will raise an error, if the string cannot be coerced
        /// ----so, use IsNumber in this same class FIRST
        /// </summary>
        /// <param name="stream">string to get int value from</param>
        /// <returns>an int object</returns>
        public static int GetInteger(string stream)
        {
            try
            {
                int number = 0; 
                if (!IsNumber(stream))
                    return number; 
                //still here? check to see if it is formatted:
                if (IsFormattedNumber(stream))
                {
                    //it's formatted; replace the format characters
                    //with nothing (retain the decimal so as not to change
                    //the intended value
                    stream = stream.Replace(m_Comma, string.Empty);
                    stream = stream.Replace(m_DollarSign, string.Empty);
                    stream = stream.Replace(m_PercentSign, string.Empty);
                }
                //we've removed superfluous formatting characters, if they
                //
did exist, now let's round it/convert it, and return it:
                number = Convert.ToInt32(stream);
                return number;
            }
            catch (Exception ex)
            {
              
//ErrorTool.ProcessError(ex);
                return 0;
            }
        } 

        /// <summary>
        /// Returns a double, as coerced from the string argument.
        /// Will raise an error, if the string cannot be coerced
        /// ----so, use IsNumber in this same class FIRST
        /// </summary>
        /// <param name="stream">string to get double value from</param>
        /// <returns>a double object</returns>
        public static double GetDouble(string stream)
        {
            try
            {
                double number = 0; 
                if (!IsNumber(stream))
                    return number; 
                //still here? check to see if it is formatted:
                if (IsFormattedNumber(stream))
                {
                    //it's formatted; replace the format characters
                    //with nothing (retain the decimal so as not to change
                    //the intended value)
                    stream = stream.Replace(m_Comma, string.Empty);
                    stream = stream.Replace(m_DollarSign, string.Empty);
                    stream = stream.Replace(m_PercentSign, string.Empty);
                }

                //we've removed superfluous formatting characters, if they
                //
did exist, now let's round it/convert it, and return it:
                number = Convert.ToDouble(stream);
                return number;
            }
            catch (Exception ex)
            {
                //ErrorTool.ProcessError(ex);
                return 0;
            }
        }

        #endregion 

        #region StringEdits
        /// <summary>
        /// Iterates thru an entire string, and sets the first letter of
        /// each word to uppercase, and all ensuing letters to lowercase
        /// </summary>
        /// <param name="stream">The string to alter the case of</param>
        /// <returns>
        /// Same string w/uppercase initial letters & others as lowercase
        /// </returns>
        public static string MixCase(string stream)
        {
            try
            {
                string newString = string.Empty;
                string character = string.Empty;
                string preceder = string.Empty;
                for (int i = 0; i < stream.Length; i++)
                {
                    character = stream.Substring(i, 1);
                    if (i > 0)
                    {
                        //look at the character immediately before current
                        preceder = stream.Substring(i - 1, 1);
                        //remove white space character from predecessor
                        if (preceder.Trim() == string.Empty)
                            //the preceding character WAS white space, so
                            //we'll change the current character to UPPER
                            character = character.ToUpper();
                        else
                            //the preceding character was NOT white space,
                            //we'll force the current character to LOWER
                            character = character.ToLower();
                    }
                    else
                        //index is 0, thus we are at the first character
                        character = character.ToUpper(); 
                    //add the altered character to the new string:
                    newString += character;
                }
                return newString;
            }
            catch (Exception ex)
            {
                //ErrorTool.ProcessError(ex);
                return null;
            }
        } 

        /// <summary>
        /// Iterates thru a string, and removes anything set to clean.
        /// Except---Does NOT remove anything in exceptionsToAllow
        /// </summary>
        /// <param name="stream">
        /// The string to clean</param>
        /// <returns>
        /// The same string, missing all elements that were set to clean
        /// (except when a character was listed in exceptionsToAllow)
        /// </returns>
        public static string Clean(string stream, bool cleanWhiteSpace,
            bool cleanDigits, bool cleanLetters, string exceptionsToAllow)
        {
            try
            {
                string newString = string.Empty;
                string character = string.Empty;
                string blessed = string.Empty; 
                if (!cleanDigits)
                    blessed += m_Digits; 
                if (!cleanLetters)
                    blessed += m_Letters; 
                blessed += exceptionsToAllow;
                //we set the comparison string to lower
                //and will compare each character's lower case version
                //against the comparison string, without
                //altering the original case of the character
                blessed = blessed.ToLower(); 
                for (int i = 0; i < stream.Length; i++)
                {
                    character = stream.Substring(i, 1); 
                    if (blessed.Contains(character.ToLower()))
                        //add the altered character to the new string:
                        newString += character;
                    else if (character.Trim() == string.Empty &&
                        !cleanWhiteSpace)
                        newString += character;
                }
                return newString;
            }
            catch (Exception ex)
            {
                //ErrorTool.ProcessError(ex);
                return null;
            }</