I am trying to make a C# program that translates unicode character from its hexadecimal format to a single character, and I have a problem. This is my code:
This works:
char e = Convert.ToChar("\u0066");
However, this doesn't work:
Console.WriteLine("enter unicode format character (for example \\u0066)");
string s = Console.ReadLine();
Console.WriteLine("you entered (for example f)");
char c = Convert.ToChar(s);
Because (Convert.ToChar("\\u0066"))
gives the error:
String must be exactly one character long
Anyone have an idea how to do this?
To insert a Unicode character, type the character code, press ALT, and then press X. For example, to type a dollar symbol ($), type 0024, press ALT, and then press X. For more Unicode character codes, see Unicode character code charts by script.
Inserting Unicode CharactersType the character code where you want to insert the Unicode symbol. Press ALT+X to convert the code to the symbol. If you're placing your Unicode character immediately after another character, select just the code before pressing ALT+X.
On your standard Mac keyboard, just type Option and the Unicode number for the character, and the character is applied to whatever text field you're currently typing in. As an example, Mac keyboards have special symbols that indicate Control, Option, and Command (Cmd).
int.Parse doesn't like the "\u" prefix, but if you validate first to ensure that it's there, you can use
char c = (char)int.Parse(s.Substring(2), NumberStyles.HexNumber);
This strips the first two characters from the input string and parses the remaining text.
In order to ensure that the sequence is a valid one, try this:
Regex reg = new Regex(@"^\\u([0-9A-Fa-f]{4})$");
if( reg.IsMatch(s) )
{
char c = (char)int.Parse(s.Substring(2), NumberStyles.HexNumber);
}
else
{
// Error
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With