user2138121
user2138121

Reputation: 75

Convert single-character string to char

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

Answers (3)

user19879142
user19879142

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

T.S.
T.S.

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

Rufus L
Rufus L

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}");

enter image description here

Upvotes: 7

Related Questions