simple unicode question

  • Thread starter Thread starter Christopher Ireland
  • Start date Start date
C

Christopher Ireland

Hi -

It's funny ... this works fine:

private void button2_Click(object sender, System.EventArgs e) {
string s = "\u0075";
char c = Convert.ToChar(s);
label1.Text = c.ToString();
}


But now imagine I want to build the string s dynamically, e.g.

private void button2_Click(object sender, System.EventArgs e) {
string s1 = "00";
string s2 = "75";
string s = "\u" + s1 + s2;
char c = Convert.ToChar(s);
label1.Text = c.ToString();
}

The code as written above gives me a design-time error under "\u" which says
"Unrecognised escape sequence". If I change "\u" to @"\u" I now get the
following runtime exception:
An unhandled exception of type 'System.FormatException' occurred in
mscorlib.dll.

Additional information: String must be only one character long.

Can anybody please tell me how I can workaround this to dynamically build a
string (like 's') and have it converted into a Unicode character?

Thanks,

Chris.
 
Hope this helps...

static void Main(string[] args)
{
// The inputs
string s1 = "00";
string s2 = "75";

// Now the conversion
short unicodeVal = System.Convert.ToInt16(s1 + s2, 16);
string unicodeCharWithinString = "" + System.Convert.ToChar(unicodeVal);

System.Console.WriteLine(unicodeCharWithinString);
System.Console.ReadLine();
}

JPRoot
 
Christopher Ireland said:
It's funny ... this works fine:

private void button2_Click(object sender, System.EventArgs e) {
string s = "\u0075";
char c = Convert.ToChar(s);
label1.Text = c.ToString();
}

Note that the middle line would be more simply written as

char c = s[0];
But now imagine I want to build the string s dynamically, e.g.

private void button2_Click(object sender, System.EventArgs e) {
string s1 = "00";
string s2 = "75";
string s = "\u" + s1 + s2;
char c = Convert.ToChar(s);
label1.Text = c.ToString();
}

The code as written above gives me a design-time error under "\u" which says
"Unrecognised escape sequence".

Absolutely. The "\uxxxx" business belongs to the compiler, not the
runtime. It's the same as trying to do:

string s = "\" + "n";

and expecting to get a newline character.
If I change "\u" to @"\u" I now get the
following runtime exception:
An unhandled exception of type 'System.FormatException' occurred in
mscorlib.dll. ?
Additional information: String must be only one character long.

Can anybody please tell me how I can workaround this to dynamically build a
string (like 's') and have it converted into a Unicode character?

Well, what do you *actually* want to get the data as? Do you really
have it as 2 2-character strings? If so, you'd use Byte.Parse twice
(using the form which allows you to specify that they're hex numbers),
shift the top byte left, and then or the results:

char c = (char)((topByte << 8)|lowByte);
 
Back
Top