Advertisement
Advertisement


How to convert/parse from String to char in java?


Question

How do I parse a String value to a char type, in Java?

I know how to do it to int and double (for example Integer.parseInt("123")). Is there a class for Strings and Chars?

2019/03/24
1
204
3/24/2019 3:49:12 AM

Accepted Answer

If your string contains exactly one character the simplest way to convert it to a character is probably to call the charAt method:

char c = s.charAt(0);
2011/10/21
298
10/21/2011 6:12:06 PM

You can use the .charAt(int) function with Strings to retrieve the char value at any index. If you want to convert the String to a char array, try calling .toCharArray() on the String.

String g = "line";
char c = g.charAt(0);  // returns 'l'
char[] c_arr = g.toCharArray(); // returns a length 4 char array ['l','i','n','e']
2018/10/15

you can use this trick :

String s = "p";

char c = s.charAt(0);
2011/10/21

If the string is 1 character long, just take that character. If the string is not 1 character long, it cannot be parsed into a character.

2011/10/21

 String string = "This is Yasir Shabbir ";
 for(char ch : string.toCharArray()){

 }

or If you want individually then you can as

char ch = string.charAt(1);

org.apache.commons.lang.StringEscapeUtils.(un)EscapeJava methods are probaby what you want

Answer from brainzzy not mine :

https://stackoverflow.com/a/8736043/1130448

2017/05/23

Source: https://stackoverflow.com/questions/7853502
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]