Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

java - 如何将char转换为String?(How to convert a char to a String?)

I have a char and I need a String .

(我有一个char ,我需要一个String 。)

How do I convert from one to the other?

(我如何从一个转换为另一个?)

  ask by Landon Kuhn translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use Character.toString(char) .

(您可以使用Character.toString(char) 。)

Note that this method simply returns a call to String.valueOf(char) , which also works.

(请注意,此方法只返回对String.valueOf(char)的调用,这也适用。)

As others have noted, string concatenation works as a shortcut as well:

(正如其他人所指出的那样,字符串连接也可以作为一种捷径:)

String s = "" + 's';

But this compiles down to:

(但这归结为:)

String s = new StringBuilder().append("").append('s').toString();

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 .

(这是效率较低的,因为StringBuilderchar[] (由StringBuilder()过度分配到16 )支持,只有由生成的String防御性地复制该String 。)

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.

(String.valueOf(char)通过将char包装在单个元素数组中并将其传递给包私有构造函数String(char[], boolean)来“获取后门”,这避免了数组副本。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...