C# Newby String to Char Conversion question

  • Thread starter Thread starter Fred Nelson
  • Start date Start date
F

Fred Nelson

Hi:

I'm more than a little confused with this question:

I need to create a char type from the first letter in a string - for
example:

string mystring;
char mychar;

mychar = (first character of mystring)

I have looked all around and find many examples of character arrays however
I can't find a simple example of how to do this - probably because it's
simple - at least I hope.

Any help with this woudl be GREATLY appreciated!

Thansk,

Fred
 
Hi Fred,

You can access each character in a string by using its indexer

char myChar = myString[index];

myString[0] would then be the first character in the string.
 
Heh Fred

This works for me, and seems straightforward enough:

string mystring = "yada";
char mychar;
mychar = mystring.ToCharArray(0,1)[0];

Cheers
Bill
 
Thanks Everyone!

Now I get it and I also understand the documentation that was showing how to
manipulate character arrays.

Fred
 
Fred Nelson said:
Thanks Everyone!

Now I get it and I also understand the documentation that was showing how
to
manipulate character arrays.

As posted by the previous posters
mychar = mystring[0]
works fine.

HOWEVER
if the string is "" //empty
You will throw an exception

Bill
 
Thanks Bill:

I have this within a try/catch!

Fred

Bill Butler said:
Fred Nelson said:
Thanks Everyone!

Now I get it and I also understand the documentation that was showing how
to
manipulate character arrays.

As posted by the previous posters
mychar = mystring[0]
works fine.

HOWEVER
if the string is "" //empty
You will throw an exception

Bill
 
Fred Nelson said:
I have this within a try/catch!

It's not a good idea to catch exceptions which can very easily be
avoided. If it's valid for the string to be empty (or null), you should
probably special case that and avoid taking the first character of it.
If it's not valid for the string to be empty or null at that point, you
should check it and throw an exception yourself.
 

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

Back
Top