+ operator doesn't concatenate Strings. Strange errors.

The following code does not work:

  String id_string = "24237751";

  String facilityCode = id_string[0] + id_string[1];

Errors:

*invalid conversion from 'int' to 'const __FlashStringHelper*' [-fpermissive]
*conversion from 'int' to 'String' is ambiguous
*no suitable constructor exists to convert from "int" to "String"

I thought that since String has element access and concatenation can be done using the + operator the above could would work. But it doesn't.

Of course I can use the substring() function and just go

String facilityCode = id_string.substring(0,3);

But wouldn't using = and + operators simplify my job ?

Is a single element of a String object still a String or is it just a char from the underlying array which cannot be concatenated using + ?

String facilityCode = String(id_string[0]) + String(id_string[1]);

But if I were using the String class (I typically don't), it seems to me that substring is more appropriate.

It is not a good idea to use the String (capital S) class on an Arduino as it can cause memory corruption in the small memory on an Arduino. This can happen after the program has been running perfectly for some time. Just use cstrings - char arrays terminated with '\0' (NULL).

And you should not try to concatenate cstrings as that will also cause memory fragmentation. You should create a global (or static local) cstring that is large enough for your longest message and then copy the parts into it - probably using strcpy()

...R