This project is read-only.

Convert char to string

Topics: Using Cosmos (Developing your own OS, projects, etc)
Nov 1, 2012 at 10:53 AM

I was trying to compare a char and a string. But I get an error message 
Operator '==' cannot be applied to operands of type 'string' and 'char'
Then I tried to convert my char to string using ToString(), (string)(myChar) and Convert.ToString(myChar), but none of this is working.


How can I do that? Please help.

Nov 1, 2012 at 11:25 PM
rddezh9 wrote:

I was trying to compare a char and a string. But I get an error message 
Operator '==' cannot be applied to operands of type 'string' and 'char'
Then I tried to convert my char to string using ToString(), (string)(myChar) and Convert.ToString(myChar), but none of this is working.


How can I do that? Please help.

Hmm try 

if(your_string.ToCharArray()[0] == your_char && your_string.length == 1)
{

	// add code here
} 

although that is weird because .ToString(); should work.. 

Nov 2, 2012 at 3:38 AM
Edited Nov 2, 2012 at 3:39 AM

you should be doing the length check first, otherwise you'll get an index out of bounds exception if the string is empty, also .ToCharArray() isn't needed, and just allocates an array when it isn't really needed, instead just do your_string[0] as that works off of the existing string object without creating a new array for the characters. (and your_char.ToString() should work just fine, though it is best to avoid creation of new strings if possible)

Nov 2, 2012 at 3:45 PM

I solved the problem with [0] after my string. I wanted to compare only first char in my string but I remembered to do that after reading your answers. So thank you!