Reputation: 75
I need to convert single string character to ASC
code, similar to Visual Basic ASC("a")
I need to do it in C#, something similar to ToCharArray()
("a").ToCharArray()
returns
{char[1]}
[0]: 97 'a'
I need to have 97 alone.
Upvotes: 1
Views: 5068
Reputation: 11
char chrReadLetter;
chrReadLetter = (char)char.ConvertToUtf32(txtTextBox1.Text.Substring(0, 1), 0);
Reads the first letter of the textbox into a character variable.
Upvotes: 1
Reputation: 19330
If you want to convert a single character string to char
, do this
char.Parse("a");
If you want to get char code do this
char.ConvertToUtf32("a", 0); // return 97
Upvotes: 2
Reputation: 37020
A string is an array of char
, so you can get the first character using array indexing syntax, and a char
, if used as an int
(which is an implicit conversion), will return the ASCII value.
Try:
int num = "a"[0]; // num will be 97
// Which is the same as using a char directly to get the int value:
int num = 'a'; // num will be 97
What you're seeing that seems to be causing some confusion is how the char
type is represented in the debugger: both the character and the int value are shown.
Here's an example of an int
and a char
in the debugger as well as in the console window (which is their ToString()
representation):
int num = "a"[0];
char chr = "a"[0];
Console.WriteLine($"num = {num}");
Console.WriteLine($"chr = {chr}");
Upvotes: 7