Cómo convertir una matriz de caracteres de nuevo a una cadena?


Tengo una matriz char:

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

Mi solución actual es hacer

String b = new String(a);

Pero seguramente hay una mejor manera de hacer esto?

Author: Sam, 2011-10-05

11 answers

No, esa solución es absolutamente correcta y muy mínima.

Tenga en cuenta, sin embargo, que esta es una situación muy inusual: Debido a que String se maneja especialmente en Java, incluso "foo" es en realidad un String. Por lo tanto, la necesidad de dividir una cadena en chars individuales y unirlas de nuevo no es necesaria en el código normal.

Compare esto con C/C++, donde "foo" usted tiene un paquete de chars terminado por un byte cero en un lado y string en el otro lado y muchas conversiones entre ellos debido a métodos heredados.

 179
Author: A.H.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-04 23:30:29

String text = String.copyValueOf(data);

O

String text = String.valueOf(data);

Es posiblemente mejor (encapsula la llamada new String).

 134
Author: David Titarenco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-09 20:31:48

Esto convertirá la matriz char de nuevo en cadena:

char[] charArray = {'a', 'b', 'c'};
String str = String.valueOf(charArray);
 35
Author: Billz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-10 19:56:37
String str = "wwwwww3333dfevvv";
char[] c = str.toCharArray();

Ahora para convertir la matriz de caracteres en cadena , hay dos maneras.

Arrays.toString(c);

Devuelve la cadena [w, w, w, w, w, w, 3, 3, 3, 3, d, f, e, v, v, v].

Y:

String.valueOf(c)

Devuelve la cadena wwwwww3333dfevvv.

 5
Author: AalekhG,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-27 11:10:01

Una cadena en java es simplemente un objeto alrededor de una matriz de caracteres. Por lo tanto, un

char[]

Es idéntico a una cadena sin caja con los mismos caracteres. Al crear una nueva cadena a partir de su matriz de caracteres

new String(char[])

Esencialmente le estás diciendo al compilador que ubique automáticamente un objeto de cadena alrededor de tu matriz de caracteres.

 4
Author: Nathan Meyer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-15 13:52:36
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]);
            }       }
    }
}
 2
Author: Ramnaresh Mantri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-04 20:28:34

Puede usar el método String.valueOf.

Por ejemplo,

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

Para obtener más información sobre la matriz de caracteres a la cadena, puede consultar los enlaces a continuación

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

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

 1
Author: Shiva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-19 10:44:57

Prueba esto

Arrays.toString(array)
 0
Author: Jessica Pereira,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-24 23:33:34

Prueba esto:

CharSequence[] charArray = {"a","b","c"};

for (int i = 0; i < charArray.length; i++){
    String str = charArray.toString().join("", charArray[i]);
    System.out.print(str);
}
 -2
Author: Curtis H,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-18 23:23:11

También puede usar la clase StringBuilder

String b = new StringBuilder(a).toString();

El uso de String o StringBuilder varía según los requisitos del método.

 -4
Author: Jagmeet Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-16 13:23:31

1 manera alternativa es hacer:

String b = a + "";
 -11
Author: Prasanna A,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-22 11:05:23