Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Force a string to ASCII encoding - remove all Unicode
//***********************************************************************************************************************************
// ForcedASCII we'll never allow Unicode that does not match to ASCII
// see https://www.cl.cam.ac.uk/~mgk25/ucs/examples/quickbrown.txt for sample text to test
//***********************************************************************************************************************************
private string ForcedASCII(string fromString)
{
string res = "";
try
{
Byte[] bytes;
Char[] chars = { ' ' };
bytes = (new System.Text.ASCIIEncoding()).GetBytes(fromString);
Array.Resize(ref chars, bytes.Length);
int ct = (new System.Text.ASCIIEncoding()).GetChars(bytes, 0, bytes.Length, chars, 0);
res = (new String(chars, 0, bytes.Length)).ToString();
}
catch (Exception)
{
res = "";
}
return res;
}
//***********************************************************************************************************************************
// ValidASCII - return true if str is a valid 8-bit ASCII string
//***********************************************************************************************************************************
private bool ValidASCII(string str)
{
return (str == ForcedASCII(str));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment