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


当前回答

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

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

其他回答

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

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

我有以下五六种方法。

// Method #1
String stringValueOf = String.valueOf('c'); // most efficient

// Method #2
String stringValueOfCharArray = String.valueOf(new char[]{x});

// Method #3
String characterToString = Character.toString('c');

// Method #4
String characterObjectToString = new Character('c').toString();

// Method #5
// Although this approach seems very simple, 
// this is less efficient because the concatenation
// expands to a StringBuilder.
String concatBlankString = 'c' + "";

// Method #6
String fromCharArray = new String(new char[]{x});

注意:Character.toString(char)返回String.valueOf(char)。所以实际上两者是一样的。

字符串。valueOf(char[] value)调用new String(char[] value),它反过来设置值char数组。

public String(char value[]) {
    this.value = Arrays.copyOf(value, value.length);
}

另一方面,字符串。valueOf(char value)调用以下包私有构造函数。

String(char[] value, boolean share) {
    // assert share : "unshared not supported";
    this.value = value;
}

Java 8中的String.java源代码

因此,就内存和速度而言,String. valueof (char)似乎是将char转换为String的最有效的方法。

来源:

如何将原始字符转换为字符串在Java 如何转换字符到字符串在Java与示例

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

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

下面是将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

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

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();