/// <summary>Removes characters of specified types.</summary>
/// <param name="source">The string to remove from.</param>
/// <param name="removeTypes">A string containing 'L' to remove letters, 'D' to remove digits and 'S' to remove symbols.</param>
/// <returns>A string containing the remaining characters.</returns>
public static string Strip(this string source, string removeTypes) {
bool letters = !string.IsNullOrEmpty(removeTypes) && removeTypes.Contains('L');
bool digits = !string.IsNullOrEmpty(removeTypes) && removeTypes.Contains('D');
bool symbols = !string.IsNullOrEmpty(removeTypes) && removeTypes.Contains('S');
StringBuilder result = new StringBuilder();
if (!string.IsNullOrEmpty(source)) {
foreach (char c in source) {
if (char.IsLetter(c)) {
if (!letters) result.Append(c);
}
else if (char.IsDigit(c)) {
if (!digits) result.Append(c);
}
else {
if (!symbols) result.Append(c);
}
}
}
return result.ToString();
}
Note that the line removeTypes.Contains(char) relies on System.Linq.
25 October 2012
Extension - Strip a string
One day I wrote this convienient extension that removes letters, digits and/or symbols - as specified - from a string:
Labels:
C#,
Extensions
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment