| 1 |
/* |
| 2 |
Adding Strings together |
| 3 |
|
| 4 |
Examples of how to add Strings together |
| 5 |
You can also add several different data types to String, as shown here: |
| 6 |
|
| 7 |
created 27 Jul 2010 |
| 8 |
modified 2 Apr 2012 |
| 9 |
by Tom Igoe |
| 10 |
|
| 11 |
This example code is in the public domain. |
| 12 |
|
| 13 |
https://www.arduino.cc/en/Tutorial/BuiltInExamples/StringAdditionOperator |
| 14 |
*/ |
| 15 |
|
| 16 |
// declare three Strings: |
| 17 |
String stringOne, stringTwo, stringThree; |
| 18 |
|
| 19 |
void setup() { |
| 20 |
// initialize serial and wait for port to open: |
| 21 |
Serial.begin(9600); |
| 22 |
while (!Serial) { |
| 23 |
; // wait for serial port to connect. Needed for native USB port only |
| 24 |
} |
| 25 |
|
| 26 |
stringOne = String("You added "); |
| 27 |
stringTwo = String("this string"); |
| 28 |
stringThree = String(); |
| 29 |
// send an intro: |
| 30 |
Serial.println("\n\nAdding Strings together (concatenation):"); |
| 31 |
Serial.println(); |
| 32 |
} |
| 33 |
|
| 34 |
void loop() { |
| 35 |
// adding a constant integer to a String: |
| 36 |
stringThree = stringOne + 123; |
| 37 |
Serial.println(stringThree); // prints "You added 123" |
| 38 |
|
| 39 |
// adding a constant long integer to a String: |
| 40 |
stringThree = stringOne + 123456789; |
| 41 |
Serial.println(stringThree); // prints "You added 123456789" |
| 42 |
|
| 43 |
// adding a constant character to a String: |
| 44 |
stringThree = stringOne + 'A'; |
| 45 |
Serial.println(stringThree); // prints "You added A" |
| 46 |
|
| 47 |
// adding a constant string to a String: |
| 48 |
stringThree = stringOne + "abc"; |
| 49 |
Serial.println(stringThree); // prints "You added abc" |
| 50 |
|
| 51 |
stringThree = stringOne + stringTwo; |
| 52 |
Serial.println(stringThree); // prints "You added this string" |
| 53 |
|
| 54 |
// adding a variable integer to a String: |
| 55 |
int sensorValue = analogRead(A0); |
| 56 |
stringOne = "Sensor value: "; |
| 57 |
stringThree = stringOne + sensorValue; |
| 58 |
Serial.println(stringThree); // prints "Sensor Value: 401" or whatever value analogRead(A0) has |
| 59 |
|
| 60 |
// adding a variable long integer to a String: |
| 61 |
stringOne = "millis() value: "; |
| 62 |
stringThree = stringOne + millis(); |
| 63 |
Serial.println(stringThree); // prints "The millis: 345345" or whatever value millis() has |
| 64 |
|
| 65 |
// do nothing while true: |
| 66 |
while (true); |
| 67 |
} |