如何将char转换为String?

我有一个char,我需要一个String。我如何从一个转换到另一个?

1225165 次浏览

您可以使用Character.toString(char)。请注意,此方法只是返回对String.valueOf(char)的调用,这也有效。

正如其他人所指出的,字符串连接也可以作为快捷方式:

String s = "" + 's';

但这可以归结为:

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

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

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

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

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

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

使用以下任何一项:

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

我有以下方法来做到这一点。

// Method #1String stringValueOf = String.valueOf('c'); // most efficient
// Method #2String stringValueOfCharArray = String.valueOf(new char[]{x});
// Method #3String characterToString = Character.toString('c');
// Method #4String 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 #6String fromCharArray = new String(new char[]{x});

注意:Character.toString(char)返回String.value(char)。所以实际上两者是相同的。

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

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

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

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

源代码从String.java inJava8源代码

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

来源:

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

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

char c = 'a';String s = String.valueOf(c);             // fastest + memory efficientString 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转换为String一个方法是在Character类中使用静态方法toString()

char ch = 'I';String str1 = Character.toString(ch);

实际上,这个toString方法在内部使用了String类中的valueOf方法,该方法使用了char数组:

public static String toString(char c) {return String.valueOf(c);}

所以第二的方法是直接使用这个:

String str2 = String.valueOf(ch);

String类中的这个valueOf方法使用了char数组:

public static String valueOf(char c) {char data[] = {c};return new String(data, true);}

所以第三的方法是使用匿名数组包装单个字符,然后将其传递给String构造函数:

String str4 = new String(new char[]{ch});

第四的方法是使用连接:

String str3 = "" + ch;

这实际上将使用StringBuilder类中的append方法,当我们在循环中进行连接时,它实际上是首选的。

以下是一些方法,没有特定的顺序:

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 aboveformatter.close();

我已经尝试了这些建议,但最终实施如下

editView.setFilters(new InputFilter[]{new InputFilter(){@Overridepublic CharSequence filter(CharSequence source, int start, int end,Spanned dest, int dstart, int dend){String prefix = "http://";
//make sure our prefix is visibleString destination = dest.toString();
//Check If we already have our prefix - make sure it doesn't//get deletedif (destination.startsWith(prefix) && (dstart <= prefix.length() - 1)){//Yep - our prefix gets modified - try preventing it.int newEnd = (dend >= prefix.length()) ? dend : prefix.length();
SpannableStringBuilder builder = new SpannableStringBuilder(destination.substring(dstart, newEnd));builder.append(source);if (source instanceof Spanned){TextUtils.copySpansFrom((Spanned) source, 0, source.length(), null, builder, newEnd);}
return builder;}else{//Accept original replacement (by returning null)return null;}}}});

我正在将Char Array转换为String

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

正如@WarFox所说-有6种方法可以将char转换为字符串。然而,最快的方法是通过连接,尽管上面的答案说它是String.valueOf。这是证明这一点的基准:

@BenchmarkMode(Mode.Throughput)@Fork(1)@State(Scope.Thread)@Warmup(iterations = 10, time = 1, batchSize = 1000, timeUnit = TimeUnit.SECONDS)@Measurement(iterations = 10, time = 1, batchSize = 1000, timeUnit = TimeUnit.SECONDS)public class CharToStringConversion {
private char c = 'c';
@Benchmarkpublic String stringValueOf() {return String.valueOf(c);}
@Benchmarkpublic String stringValueOfCharArray() {return String.valueOf(new char[]{c});}
@Benchmarkpublic String characterToString() {return Character.toString(c);}
@Benchmarkpublic String characterObjectToString() {return new Character(c).toString();}
@Benchmarkpublic String concatBlankStringPre() {return c + "";}
@Benchmarkpublic String concatBlankStringPost() {return "" + c;}
@Benchmarkpublic String fromCharArray() {return new String(new char[]{c});}}

和结果:

Benchmark                                        Mode  Cnt       Score      Error  UnitsCharToStringConversion.characterObjectToString  thrpt   10   82132.021 ± 6841.497  ops/sCharToStringConversion.characterToString        thrpt   10  118232.069 ± 8242.847  ops/sCharToStringConversion.concatBlankStringPost    thrpt   10  136960.733 ± 9779.938  ops/sCharToStringConversion.concatBlankStringPre     thrpt   10  137244.446 ± 9113.373  ops/sCharToStringConversion.fromCharArray            thrpt   10   85464.842 ± 3127.211  ops/sCharToStringConversion.stringValueOf            thrpt   10  119281.976 ± 7053.832  ops/sCharToStringConversion.stringValueOfCharArray   thrpt   10   86563.837 ± 6436.527  ops/s

如你所见,最快的是c + """" + c

VM version: JDK 1.8.0_131, VM 25.131-b11

这种性能差异是由于-XX:+OptimizeStringConcat优化造成的。您可以阅读有关它的信息这里

  char vIn = 'A';String vOut = Character.toString(vIn);

对于这些类型的转换,我有一个站点书签称为https://www.converttypes.com/它可以帮助我快速获得我使用的大多数语言的转换代码。