Update: these will work best as Extension Methods when used with .NET 3.5
These are 6 free and useful .NET string manipulation functions (methods) that you will find handy in most of your applications.
- Space - given a number, will return a string with that number of spaces in it.
- LeadingZeros - given a string (typically a string representation of a number), will return a string of the length specified, with zeros filling any "empty space" to the left.
- Right - given a length and a string, will return only the rightmost characters of that string, up to the length specified. If the string is shorter than the length specified, it will just return the original string.
- Left - given a length and a string, will return only the leftmost characters of that string, up to the length specified. If the string is shorter than the length specified, it will just return the original string.
- StripNonNumeric - given a string, will return a string with all numeric characters removed.
- Strip - given a source string and a strip string, will return a string with all instances of the (contiguous) strip string removed.
Don't forget to include the
System.Text.RegularExpressions namespace if you use the
StripNonNumeric method.
public static string Space(int width)
{
return String.Empty.PadLeft(width);
}
public static string LeadingZeros(string number, short length)
{
return number.Length < length ? number.PadLeft(length, '0') : number;
}
public static string Right(string value, int length)
{
return value.Length > length ? value.Substring(value.Length - length, length) : value;
}
public static string Left(string value, int length)
{
return value.Length > length ? value.Substring(0, length) : value;
}
public static string StripNonNumeric(string value)
{
return String.Join("", Regex.Split(value, @"[\D]"));
}
public static string Strip(string sourceValue, string stripValue)
{
string[] stripValues = { stripValue };
return String.Join("", sourceValue.Split(stripValues, StringSplitOptions.None));
}
If you found this post helpful, please "Kick" it so others can find it too: