Convert a String to a char...

G

Guest

Hi

There is any easy way to convert a 1Char string to a char variable
string str="A"
char ch=str..

Thanks for your help
 
B

Bjorn Abelli

...
There is any easy way to convert a 1Char string to a char variable?
string str="A";
char ch=str...

This gets the first character in the string:

char ch = str[0];

// Bjorn A
 
M

Marc Lörner

Hi Bernardo,
Bernardo said:
Hi,

There is any easy way to convert a 1Char string to a char variable?
string str="A";
char ch=str...

Thanks for your help,

try:
string str = "A";

char ch = Convert.ToChar(str);

HTH,
Marc
 
M

Mark Broadbent

remember that string is an array of char, therefore you can access each
element by its index.

e.g.

string s = "abc";

char ch = s[0];


--

--

Br,
Mark Broadbent
mcdba , mcse+i
=============
 
M

Mark Broadbent

bear in mind Bernardo that if you try the conversion using Convert and the
string is greater than 1 char or null then an exception will be thrown,
likewise if you try accessing the 0 index of the string and the string is
empty or null then an exception will also be thrown.

--

--

Br,
Mark Broadbent
mcdba , mcse+i
=============
 
J

Jon Skeet [C# MVP]

Mark Broadbent said:
remember that string is an array of char, therefore you can access each
element by its index.

e.g.

string s = "abc";

char ch = s[0];

No, a string isn't actually an array of chars. However, it has an
indexer which returns the character at the appropriate position.
 
M

Mark Broadbent

thx for correction. had read that one time but obviously hadnt sunk in (it
also explains the immutable aspect of strings).

cheers.

--

--

Br,
Mark Broadbent
mcdba , mcse+i
=============
Jon Skeet said:
Mark Broadbent said:
remember that string is an array of char, therefore you can access each
element by its index.

e.g.

string s = "abc";

char ch = s[0];

No, a string isn't actually an array of chars. However, it has an
indexer which returns the character at the appropriate position.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top