5

I am using Arduino. I would like to append a String object to an array of characters.

String msg = "ddeeff"

char charArr[1600];

//assume charArr already contains some string
//How can I do something like this to append String to charArray?
charArr = charArr + msg;

2 Answers 2

4

This will work for Arduino String object.

strcat( charArr, msg.c_str() );

String object msg gets converted into an array of characters with the String method c_str(). Then, you can use strcat() to append the 2 arrays of characters.

As mentioned by Rakete1111, it is undefined behavior if charArr is not big enough

Sign up to request clarification or add additional context in comments.

2 Comments

Be careful though, it is undefined behavior if charArr is not big enough.
char charArr[1600]; might rather be too big for a "standard" Arduino UNO, depending on other local variable requirements etc. Be careful in that direction, too. Behavior is undefined as well. ;)
1

String has a operator+ which takes a const char*, and it also has a c_str() function, which converts it to a const char*.

You can combine them to get the desired result:

String temp = charrArr + msg; //Store result in a String

//Copy every character
std::strncpy(charArr, temp.c_str(), sizeof(charrArr));

1 Comment

Now charArr may not contain the terminating '\0'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.