Given a character and we have to convert it to the string in Java.
给定一个字符,我们必须将其转换为Java中的字符串。
Java char到字符串的转换 (Java char to string conversion)
There are two ways to convert a character to the string in Java, which are,
在Java中,有两种方法可以将字符转换为字符串:
Using String.valueOf(character) method
使用String.valueOf(character)方法
Using Character.toString(character) method
使用Character.toString(character)方法
1) Java char to string example: Using String.valueOf(character) method
1)Java char转换为字符串的示例:使用String.valueOf(character)方法
valueOf() method is a String class method, it accepts a character (character array also) and returns the string.
valueOf()方法是String类方法,它接受一个字符(也为字符数组)并返回字符串。
Example:
例:
public class Main
{
public static void main(String[] args) {
char char_value = 'X';
String str ="";
//converting from char to string
str = String.valueOf(char_value);
//printing value
System.out.println("str = " + str);
}
}
Output
输出量
str = X
Java char to string example: Using Character.toString(character) method
Java char to string示例:使用Character.toString(character)方法
toString() method is a Character class method, it accepts the character (character array also) and returns the string.
toString()方法是Character类方法,它接受字符(也为字符数组)并返回字符串。
Example:
例:
public class Main
{
public static void main(String[] args) {
char char_value = 'X';
String str ="";
//converting from char to string
str = Character.toString(char_value);
//printing value
System.out.println("str = " + str);
}
}
Output
输出量
str = X
翻译自: https://www.includehelp.com/java/convert-a-character-to-the-string-in-java.aspx