You cannot add C strings (i.e. NUL-terminated arrays of char
) with the
+
operator. It only works with String
objects. You can, though, add
a String object and a C-string, because in this case the compiler
implicitly converts the C string into a String object:
String phone_number = "901234567";
phone_number = "+" + phone_number;
The last line is interpreted by the compiler as
phone_number = String("+") + phone_number;
That being said, I encourage you to try to avoid String objects if
possible. These use dynamic memory allocation which carries the risk of
heap fragmentation. The same thing can be achieved with plain C strings:
char phone_number[] = "901234567";
char full_phone_number[strlen(phone_number) + 2];
strcpy(full_phone_number, "+");
strcat(full_phone_number, phone_number);
Note the size of the second string: strlen(phone_number) + 2
. You need
one extra char
for the +
sign, and another one for the NUL string
terminator.
Now, with C strings you can do better, and avoid copying: reserve enough
room in an array for the full number (“+” included), and then fill the
digits starting from the second slot in the char
array. You can then
add the +
sign later:
char phone_number[16];
strcpy(phone_number + 1, "901234567");
phone_number[0] = '+';
Although I personally would write the “+” sign and a NUL while
initializing the array:
char phone_number[16] = "+";
strcat(phone_number, "901234567");