我有一个字符,我需要一个字符串。我如何从一个转换到另一个?


当前回答

以下是一些方法,排名不分先后:

char c = 'c';

String s = Character.toString(c); // Most efficient way

s = new Character(c).toString(); // Same as above except new Character objects needs to be garbage-collected

s = c + ""; // Least efficient and most memory-inefficient, but common amongst beginners because of its simplicity

s = String.valueOf(c); // Also quite common

s = String.format("%c", c); // Not common

Formatter formatter = new Formatter();
s = formatter.format("%c", c).toString(); // Same as above
formatter.close();

其他回答

我正在将字符数组转换为字符串

Char[] CharArray={ 'A', 'B', 'C'};
String text = String.copyValueOf(CharArray);

像这样使用Character.toString()方法:

char mChar = 'l';
String s = Character.toString(mChar);

使用以下任何一种方法:

String str = String.valueOf('c');
String str = Character.toString('c');
String str = 'c' + "";

试试这个:Character.toString(aChar)或这样:aChar + ""

下面是将char c转换为String s的各种方法(以速度和效率为递减顺序)

char c = 'a';
String s = String.valueOf(c);             // fastest + memory efficient
String s = Character.toString(c);
String s = new String(new char[]{c});
String s = String.valueOf(new char[]{c});
String s = new Character(c).toString();
String s = "" + c;                        // slowest + memory inefficient