Reputation: 78481
I have a char
and I need a String
. How do I convert from one to the other?
Upvotes: 953
Views: 1292538
Reputation: 436
Just chipping in to add that with rust 1.46.0 you can convert a char into a string like so:
let string = String::from('a');
Upvotes: -1
Reputation: 6266
To convert a char
to a String
, you can use the String.valueOf
method.
To convert a String
to a char
, you can use the String.charAt
method.
char character = 'a';
String string = String.valueOf(character);
String string = "a";
char character = string.charAt(0);
Upvotes: -2
Reputation: 4973
I've got of the following five six methods to do it.
// 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});
Note: Character.toString(char) returns String.valueOf(char). So effectively both are same.
String.valueOf(char[] value)
invokes new String(char[] value)
, which in turn sets the value
char array.
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
On the other hand String.valueOf(char value)
invokes the following package private constructor.
String(char[] value, boolean share) {
// assert share : "unshared not supported";
this.value = value;
}
Source code from String.java
in Java 8 source code
Hence
String.valueOf(char)
seems to be most efficient method, in terms of both memory and speed, for convertingchar
toString
.
Sources:
Upvotes: 277
Reputation: 729
char vIn = 'A';
String vOut = Character.toString(vIn);
For these types of conversion, I have site bookmarked called https://www.converttypes.com/ It helps me quickly get the conversion code for most of the languages I use.
Upvotes: 1
Reputation: 3063
Use the Character.toString()
method like so:
char mChar = 'l';
String s = Character.toString(mChar);
Upvotes: 33
Reputation: 12837
As @WarFox stated - there are 6 methods to convert char to string. However, the fastest one would be via concatenation, despite answers above stating that it is String.valueOf
. Here is benchmark that proves that:
@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';
@Benchmark
public String stringValueOf() {
return String.valueOf(c);
}
@Benchmark
public String stringValueOfCharArray() {
return String.valueOf(new char[]{c});
}
@Benchmark
public String characterToString() {
return Character.toString(c);
}
@Benchmark
public String characterObjectToString() {
return new Character(c).toString();
}
@Benchmark
public String concatBlankStringPre() {
return c + "";
}
@Benchmark
public String concatBlankStringPost() {
return "" + c;
}
@Benchmark
public String fromCharArray() {
return new String(new char[]{c});
}
}
And result:
Benchmark Mode Cnt Score Error Units
CharToStringConversion.characterObjectToString thrpt 10 82132.021 ± 6841.497 ops/s
CharToStringConversion.characterToString thrpt 10 118232.069 ± 8242.847 ops/s
CharToStringConversion.concatBlankStringPost thrpt 10 136960.733 ± 9779.938 ops/s
CharToStringConversion.concatBlankStringPre thrpt 10 137244.446 ± 9113.373 ops/s
CharToStringConversion.fromCharArray thrpt 10 85464.842 ± 3127.211 ops/s
CharToStringConversion.stringValueOf thrpt 10 119281.976 ± 7053.832 ops/s
CharToStringConversion.stringValueOfCharArray thrpt 10 86563.837 ± 6436.527 ops/s
As you can see, the fastest one would be c + ""
or "" + c
;
VM version: JDK 1.8.0_131, VM 25.131-b11
This performance difference is due to -XX:+OptimizeStringConcat
optimization. You can read about it here.
Upvotes: 19
Reputation: 2234
I am converting Char Array to String
Char[] CharArray={ 'A', 'B', 'C'};
String text = String.copyValueOf(CharArray);
Upvotes: 2
Reputation: 172
I've tried the suggestions but ended up implementing it as follows
editView.setFilters(new InputFilter[]{new InputFilter()
{
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend)
{
String prefix = "http://";
//make sure our prefix is visible
String destination = dest.toString();
//Check If we already have our prefix - make sure it doesn't
//get deleted
if (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;
}
}
}});
Upvotes: 0
Reputation: 22471
Below are various ways to convert to char c to String s (in decreasing order of speed and efficiency)
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
Upvotes: 59
Reputation: 5425
Here are a few methods, in no particular order:
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();
Upvotes: 4
Reputation: 24167
We have various ways to convert a char
to String
. One way is to make use of static method toString()
in Character
class:
char ch = 'I';
String str1 = Character.toString(ch);
Actually this toString
method internally makes use of valueOf
method from String
class which makes use of char array:
public static String toString(char c) {
return String.valueOf(c);
}
So second way is to use this directly:
String str2 = String.valueOf(ch);
This valueOf
method in String
class makes use of char array:
public static String valueOf(char c) {
char data[] = {c};
return new String(data, true);
}
So the third way is to make use of an anonymous array to wrap a single character and then passing it to String
constructor:
String str4 = new String(new char[]{ch});
The fourth way is to make use of concatenation:
String str3 = "" + ch;
This will actually make use of append
method from StringBuilder
class which is actually preferred when we are doing concatenation in a loop.
Upvotes: 5
Reputation: 55233
You can use Character.toString(char)
. Note that this method simply returns a call to String.valueOf(char)
, which also works.
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
.
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.
Upvotes: 701
Reputation: 60424
Use any of the following:
String str = String.valueOf('c');
String str = Character.toString('c');
String str = 'c' + "";
Upvotes: 34
Reputation: 236112
Try this: Character.toString(aChar)
or just this: aChar + ""
Upvotes: 18