Skip to content

Instantly share code, notes, and snippets.

@gojimmypi
Created July 31, 2019 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gojimmypi/5b9a0c1360418ed40029b6a2596ea4a0 to your computer and use it in GitHub Desktop.
Save gojimmypi/5b9a0c1360418ed40029b6a2596ea4a0 to your computer and use it in GitHub Desktop.
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