Convert a String to a char in Java
This post will discuss how to convert a string containing exactly one character to its equivalent primitive char value in Java. If the string contains more than one character, the solution should copy the character present at the first index.
1. Using String.charAt() method
The idea is to call the charAt(int) method on the specified string to retrieve the character value present at the first index. This is a standard approach to convert a string to a char in Java.
|
1 2 3 |
public static char StringToChar(String s) { return s.charAt(0); } |
2. Using String.toCharArray() method
Another approach is to convert the string into a character array by using String.toCharArray() and simply return the element present at the first index.
|
1 2 3 |
public static char StringToChar(String s) { return s.toCharArray()[0]; } |
In Java 8 we can do like,
|
1 2 3 4 5 |
public static char StringToChar(String s) { return s.chars() // IntStream .mapToObj(ch -> (char) ch) // Stream<Character> .toArray(Character[]::new)[0]; // Character[] } |
We can save some time (and memory) if we only need to print the character:
|
1 2 3 4 |
public static char StringToChar(String s) { s.chars().limit(1) .forEach(c -> System.out.print((char)c)); } |
3. Using String.codePointAt() method
We can also use the String.codePointAt() method that returns the code point value of the character present at the specified index.
|
1 2 3 |
public static char StringToChar(String s) { return (char)s.codePointAt(0); } |
We can also use String.codePointBefore() method, which is similar to String.codePointAt() method, except it returns the code point value of the character present before the specified index.
|
1 2 3 |
public static char StringToChar(String s) { return (char)s.codePointBefore(1); } |
4. Using String.getChars() method
Here, the idea is to construct an empty char array of size 1 and fill it with the first character of the string using the String.getChars() method.
|
1 2 3 4 5 |
public static char StringToChar(String s) { char[] dest = new char[1]; s.getChars(0, 1, dest, 0); return dest[0]; } |
That’s all about converting a String to a char in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)