You're getting read-only strings of type const char*
from your JSON parser - that's OK. You can concatenate them without restriction, but you have to provide memory to hold the result of the concatenation.
There are a few ways to solve this
strncat()
(good old-fashioned C). Have a look at this thread explaining strcat(). In essence, allocate enough memory to hold the new string and then store the concatenation result there (error handling omitted for clarity). Assuming the strings you want to concatenate are str1
and str2
:
const size_t cat_buf_len = strlen(str1) + strlen(str2) + 1;
char* cat_buf = (char*) malloc(cat_buf_len);
strncpy(cat_buf, str1, cat_buf_len);
strncat(cat_buf, str2, cat_buf_len - strlen(cat_buf));
// ... use the concatenated string in cat_buf
free(cat_buf);
snprintf()
(C). Similar to strcat()
- a bit easier on the eyes, but not as efficient.
const size_t cat_buf_len = strlen(str1) + strlen(str2) + 1;
char* cat_buf = (char*) malloc(cat_buf_len);
snprintf(cat_buf, cat_buf_len, "%s%s", str1, str2);
// ... use the concatenated string in cat_buf
free(cat_buf);
- Arduino
String
(C++). The String type operates on heap, manages its own memory and is a bit easier to use. It does risk fragmenting the heap, though, if not used carefully.
String cat_str = String(str1) + str2;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…