How to convert a char array back to a string?

2019-01-02 19:08发布

I have a char array:

char[] a = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};

My current solution is to do

String b = new String(a);

But surely there is a better way of doing this?

11条回答
旧时光的记忆
2楼-- · 2019-01-02 19:34

Try this

Arrays.toString(array)
查看更多
回忆,回不去的记忆
3楼-- · 2019-01-02 19:36

You can use String.valueOf method.

For example,

char[] a = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
String b = String.valueOf(a);
System.out.println("Char Array back to String is: " + b);

For more on char array to string you can refer links below

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html

https://www.flowerbrackets.com/char-array-to-string-java/

查看更多
与君花间醉酒
4楼-- · 2019-01-02 19:38

This will convert char array back to string:

char[] charArray = {'a', 'b', 'c'};
String str = String.valueOf(charArray);
查看更多
泪湿衣
5楼-- · 2019-01-02 19:38

1 alternate way is to do:

String b = a + "";
查看更多
十年一品温如言
6楼-- · 2019-01-02 19:40

A String in java is merely an object around an array of chars. Hence a

char[]

is identical to an unboxed String with the same characters. By creating a new String from your array of characters

new String(char[])

you are essentially telling the compiler to autobox a String object around your array of characters.

查看更多
时光乱了年华
7楼-- · 2019-01-02 19:40
package naresh.java;

public class TestDoubleString {

    public static void main(String args[]){
        String str="abbcccddef";    
        char charArray[]=str.toCharArray();
        int len=charArray.length;

        for(int i=0;i<len;i++){
            //if i th one and i+1 th character are same then update the charArray
            try{
                if(charArray[i]==charArray[i+1]){
                    charArray[i]='0';                   
                }}
                catch(Exception e){
                    System.out.println("Exception");
                }
        }//finally printing final character string
        for(int k=0;k<charArray.length;k++){
            if(charArray[k]!='0'){
                System.out.println(charArray[k]);
            }       }
    }
}
查看更多
登录 后发表回答