This is just a code dump of some useful string extension methods that I make use of daily. Use it, dont use it...:)
public static class StringExtensions
{
public static string Left(this string str, int length)
{
return (str.Substring(0, length < str.Length ? length : str.Length));
}
public static string Right(this string str, int length)
{
return (str.Substring(length < str.Length ? str.Length - length : 0));
}
public static string Reverse(this string str)
{
char[] c = str.ToCharArray();
Array.Reverse(c);
return new string(c);
}
public static string ToSentenceCase(this string str)
{
string returnValue = str.Left(1).ToUpper();
if (str.Length > 1)
returnValue += str.Substring(1).ToLower();
return (returnValue);
}
public static string ToProperCase(this string str)
{
var returnValue = new StringBuilder();
string[] values = str.Split(' ');
foreach (string s in values)
returnValue.Append(s.ToSentenceCase() + " ");
return (returnValue.ToString().Left(str.Length));
}
public static bool IsAlphaNumeric(this string inputString)
{
if (inputString == null) return false;
return Regex.Matches(inputString, "[^A-Za-z0-9]$").Count == 0;
}
public static string StripNonAlphaNumeric(this string inputString, string replacement)
{
if (inputString == null) return null;
return Regex.Replace(inputString, "[^A-Za-z0-9]", replacement, RegexOptions.None);
}
public static string StripNonNumeric(this string inputString, string replacement)
{
if (inputString == null) return null;
return Regex.Replace(inputString, "[^\\.\\-0-9]", replacement, RegexOptions.None);
}
public static string TruncateAndTrim(this string str, int length)
{
return (str.Trim().Left(length));
}
}