Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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)来“获取后门”,这避免了数组副本。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...