I've developed a client library to integrate with a couriers shipping API. The courier only accepts a limited set of characters for addresses, so I've created a helper class to strip out invalid characters and optionally replace them (with for example a ?).
public static class StringCleaner
{
private static readonly char[] ValidCharacters =
{
' ', '#', '&', '\'', '(', ')', '+', ',', '-', '.', '/',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
':', '?', '@',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'[', ']', '_', '`',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'{', '|', '}', '~',
};
public static string CleanString(string stringToClean, string replacement = "")
{
int length = stringToClean.Length;
var newString = new StringBuilder();
for (var i = 0; i < length; i++)
{
if (ValidCharacters.Contains(stringToClean[i]))
{
newString.Append(stringToClean[i]);
}
else
{
newString.Append(replacement);
}
}
return newString.ToString();
}
}