如何将char转换为Java中的字符串? [英] How to convert a char to a string in Java?

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

问题描述

我有一个 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.

这篇关于如何将char转换为Java中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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