如何将字符转换为字符串? [英] How to convert a char to a String?

查看:213
本文介绍了如何将字符转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个char,我需要一个String.如何从一个转换为另一个?

I have a char and I need a String. How do I convert from one to the other?

推荐答案

您可以使用 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();

效率较低,因为StringBuilderchar[]支持(由

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.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆