2011-09-12 16 views
61

Ricevo un valore int da uno dei pin analogici sul mio Arduino. Come concatenarlo a un String e quindi convertire il String in un char[]?Conversione di int o String in un array di caratteri su Arduino

È stato suggerito di provare char msg[] = myString.getChars();, ma sto ricevendo un messaggio che getChars non esiste.

+5

Avete davvero bisogno di un allineamento modificabile? Altrimenti, potresti usare 'const char * msg = myString.c_str();'. A differenza di 'toCharArray()', 'c_str()' è un'operazione di copia zero e la copia zero è una buona cosa su dispositivi con vincoli di memoria. –

risposta

99
  1. Per convertire e aggiungere un numero intero, utilizzare operator += (o funzione membro concat):

    String stringOne = "A long integer: "; 
    stringOne += 123456789; 
    
  2. Per ottenere la stringa come tipo char[], utilizzare toCharArray():

    char charBuf[50]; 
    stringOne.toCharArray(charBuf, 50) 
    

Nell'esempio, c'è solo spazio per 49 caratteri (presumendo che sia terminato da null). Potresti voler rendere le dimensioni dinamiche.

+11

Mi ha salvato un sacco di tempo per armeggiare. Grazie! Per rendere dinamico il carattere [], fare qualcosa come 'char charBuf [stringOne.length() + 1]' – loeschg

+8

L'ho fatto dinamicamente in questo modo: 'char ssid [ssidString.length()];' 'ssidString.toCharArray (ssid, ssidString.length());' – dumbledad

+1

@loeschg Grazie, ho provato senza il '+ 1' all'inizio, ma la soluzione ha funzionato per me! –

39

Proprio come un riferimento, ecco un esempio di come per la conversione tra String e char[] con una lunghezza dinamica -

// Define 
String str = "This is my string"; 

// Length (with one extra character for the null terminator) 
int str_len = str.length() + 1; 

// Prepare the character array (the buffer) 
char char_array[str_len]; 

// Copy it over 
str.toCharArray(char_array, str_len); 

Sì, questo è dolorosamente ottusa per qualcosa di semplice come una conversione di tipo, ma purtroppo è il modo più semplice.

0

Nessuno di quelli ha funzionato. Ecco un modo molto più semplice .. lo str etichetta è il puntatore a quello che è un array ...

String str = String(yourNumber, DEC); // Obviously .. get your int or byte into the string 

str = str + '\r' + '\n'; // Add the required carriage return, optional line feed 

byte str_len = str.length(); 

// Get the length of the whole lot .. C will kindly 
// place a null at the end of the string which makes 
// it by default an array[]. 
// The [0] element is the highest digit... so we 
// have a separate place counter for the array... 

byte arrayPointer = 0; 

while (str_len) 
{ 
    // I was outputting the digits to the TX buffer 

    if ((UCSR0A & (1<<UDRE0))) // Is the TX buffer empty? 
    { 
     UDR0 = str[arrayPointer]; 
     --str_len; 
     ++arrayPointer; 
    } 
} 
+0

'str' non è puntatore a un array, è un oggetto' String' che implementa l'operatore '[]'. –

Problemi correlati