
-----------------------------------
elmocookies
Mon Jun 09, 2008 6:10 pm

Assigning a string value to a char
-----------------------------------
I've been trying to assign a string (consonantString) to a char (consonantChar). I found and tried using the following code:


String consonantString = (new Character(consonantChar)).toString();


Since the code assigns a char to a string, I tried changing it so it assigned a string to a char and I ended up with:


Char consonantChar = (new String(consonantString)).toChar();


However, the to.Char() caused an error and the program said I should use toCharArray(); instead. When I tried that, it didn't work either.

Does anyone know how I can fix that?

Thanks in advance.

-----------------------------------
OneOffDriveByPoster
Mon Jun 09, 2008 6:15 pm

Re: Assigning a string value to a char
-----------------------------------
Strings can have multiple characters.  In your case, constantString.charAt(0) is probably what you want.

-----------------------------------
jeffgreco13
Tue Jun 10, 2008 8:01 am

Re: Assigning a string value to a char
-----------------------------------
wouldn't you have to declare the constantChar variable as an array?

-----------------------------------
DemonWasp
Fri Jun 13, 2008 9:22 am

RE:Assigning a string value to a char
-----------------------------------
As per http://java.sun.com/javase/6/docs/api/ , there IS no toChar() method in String. If you want a single character out of the string, then you should, as OneOff said, use charAt(index) instead. If you want the string as an array of characters, then you should use toCharArray(), which returns a char[] - so constantChar would have to be a char[], as jeffgreco said.

You also don't need that (new String(existingString)).someMethod() nonsense. You can just use existingString.someMethod().
