Convert string to character array in Arduino


There are several libraries built for Arduino whose functions take in character arrays as inputs instead of strings. Thankfully, Arduino has an inbuilt method (toCharArray()) to covert a String to a Character Array. A sample implementation is given below −

Example

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   String s1 = "Hello World!";
   char buf[30];

   s1.toCharArray(buf,6);
   Serial.println(buf);

   s1.toCharArray(buf,s1.length());
   Serial.println(buf);
}
void loop() {
   // put your main code here, to run repeatedly:
}

As you can see, the toCharArray function takes in two arguments, the array in which the characters of the strings are to be stored, and the number of characters to convert. We are initially converting only the first 5 characters of the string to a char array. Please note that we have specified 6 as the length instead of 5, because the last character is reserved for the string termination character ('0'). Thus, if you want the string to contain N characters, enter N+1 in the length argument.

This means that the first print statement will print only "Hello". In the next attempt, the entire string will get printed, as we have specified the length argument to be equal to the length of the string. But, as you can notice from the output below, the exclamation mark (!) at the end is missing. Again, this is because ideally, we should have specified the length argument to be length of the string + 1. Make sure that you don't convert more characters than what your char array can store.

The Serial Monitor output is shown below −

Output

Updated on: 24-Mar-2021

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements