Skip to content

Instantly share code, notes, and snippets.

@JonTargaryen
Forked from gojimmypi/ForcedAscii.cs
Created August 10, 2019 01:20
Show Gist options
  • Save JonTargaryen/a56d483b344fc77540f9d37a50d70f59 to your computer and use it in GitHub Desktop.
Save JonTargaryen/a56d483b344fc77540f9d37a50d70f59 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