You can add Strings together in a variety of ways. This is called concatenation and it results in the original String being longer by the length of the String or character array with which you concatenate it. The +
operator allows you to combine a String with another String, with a constant character array, an ASCII representation of a constant or variable number, or a constant character.
stringThree = stringOne + 123;
// adding a constant long interger to a string:
stringThree = stringOne + 123456789;
// adding a constant character to a string:
stringThree = stringOne + ‘A’;
// adding a constant string to a string:
stringThree = stringOne + “abc”;
// adding two Strings together:
stringThree = stringOne + stringTwo;
You can also use the +
operator to add the results of a function to a String, if the function returns one of the allowed data types mentioned above. For example,
This is allowable since the millis()
function returns a long integer, which can be added to a String. You could also do this:
because analogRead()
returns an integer. String concatenation can be very useful when you need to display a combination of values and the descriptions of those values into one String to display via serial communication, on an LCD display, over an Ethernet connection, or anywhere that Strings are useful.
Caution: You should be careful about concatenating multiple variable types on the same line, as you may get unexpected results. For example:
String stringOne = “Sensor value: “;
String stringThree = stringOne + sensorValue;
Serial.println(stringThree);
results in “Sensor Value: 402” or whatever the analogRead()
result is, but
String stringThree = “Sensor value: ” + sensorValue;
Serial.println(stringThree);
gives unpredictable results because stringThree
never got an initial value before you started concatenating different data types.
Here’s another example where improper initialization will cause errors:
This won’t compile because the compiler doesn’t handle the operator precedence correctly. On the other hand, the following will compile, but it won’t run as expected:
For more detail: Arduino String Addition Operator Code