ChatGPT解决这个技术问题 Extra ChatGPT

How to convert a char to a String?

I have a char and I need a String. How do I convert from one to the other?

Downvoted? Why would I ask such an easy question? Because Google lacks a really obvious search result for this question. By putting this here we'll change that.
i completely agree with your opinion. I up voted this to get rid of the negative vote. I firmly believe in making googling topics like this easier for everyone. =)
Did your research include reading the documentation of the String class?
@DJClayworth Most SO questions could be answered with RTFM, but that's not very helpful. Why not let people who find the question upvote it and let things take their course?
@PaulBellora Only that StackOverflow has become the first stop for research. If there is a StackOverlfow link in the first 10 Google Results I com here.

P
Paul Bellora

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.


I think the shortcut compiles down to: new StringBuilder("").append('s').toString();
@BinkanSalaryman using javac 1.8.0_51-b16 and then javap to decompile, I see the constructor/method calls I have in the answer. What are you using?
x
xagyg

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 converting char to String.

Sources:

How to convert primitive char to String in Java How to convert Char to String in Java with Example


s
sactiw

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

someone tested this?
b
byxor

Use the Character.toString() method like so:

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

W
Wayne

Use any of the following:

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

D
Dmitriy Dumanskiy

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.


Ó
Óscar López

Try this: Character.toString(aChar) or just this: aChar + ""


a
akhil_mittal

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.


h
hyper-neutrino

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

P
Py-Coder

I am converting Char Array to String

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

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
I am Converting Char Array to String @pczeus
F
Firzok Nadeem
  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.


z
zmicer

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