如何将字符转换为字符串? [英] How to convert a char to a String?
问题描述
我有一个 char
,我需要一个 String
.我如何从一种转换到另一种?
I have a char
and I need a String
. How do I convert from one to the other?
推荐答案
您可以使用 Character.toString(char)
.请注意,此方法仅返回对 String.valueOf(char)
,同样有效.
You can use Character.toString(char)
. Note that this method simply returns a call to String.valueOf(char)
, which also works.
正如其他人所指出的,字符串连接也可以作为一种快捷方式:
As others have noted, string concatenation works as a shortcut as well:
String s = "" + 's';
但这可以归结为:
String s = new StringBuilder().append("").append('s').toString();
效率较低,因为 StringBuilder
由 char[]
支持(由 StringBuilder()
到 16
),仅用于由结果 String
防御性复制该数组.
which is less efficient because the StringBuilder
is backed by a char[]
(over-allocated by StringBuilder()
to 16
), only for that array to be defensively copied by the resulting String
.
String.valueOf(char)
通过将 char
包装在一个单元素数组中并将其传递给包私有构造函数 String(char[], boolean)
,避免了数组复制.
String.valueOf(char)
"gets in the back door" by wrapping the char
in a single-element array and passing it to the package private constructor String(char[], boolean)
, which avoids the array copy.
这篇关于如何将字符转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!