How to convert/parse from String to char in java?
In Java, you can convert a string to a character using the charAt()
method of the String
class. This method takes an index as an argument and returns the character at that index.
For example:
String str = "hello";
char ch = str.charAt(0); // ch will be 'h'
You can also use the toCharArray()
method to convert a string to an array of characters:
String str = "hello";
char[] chars = str.toCharArray(); // chars will be ['h', 'e', 'l', 'l', 'o']
Note that if you want to convert a single-character string to a character, you can simply use the char
type's parse method, like this:
String str = "h";
char ch = str.charAt(0); // ch will be 'h'
You can also use the char
type's parse method to convert a string to a character:
String str = "h";
char ch = Character.parseChar(str); // ch will be 'h'
Finally, you can use the Character.toString()
method to convert a character to a string:
char ch = 'h';
String str = Character.toString(ch); // str will be "h"