How to Use Strings in Arduino: Syntax and Examples
In Arduino, you can use
String objects to work with text easily or use character arrays (char[]) for more control. Use String for simple text handling and char[] when memory is limited or you need C-style strings.Syntax
Arduino supports two main ways to use strings: String objects and character arrays. String is a class that lets you work with text easily, while char[] is a traditional C-style string stored as an array of characters ending with a null character '\0'.
Here is the basic syntax for both:
arduino
String myString = "Hello, Arduino!"; char myCharArray[] = "Hello, Arduino!";
Example
This example shows how to create a String, append text, and print it to the Serial Monitor.
arduino
void setup() { Serial.begin(9600); String greeting = "Hello"; greeting += ", Arduino!"; // Add text to the string Serial.println(greeting); // Prints: Hello, Arduino! } void loop() { // Nothing here }
Output
Hello, Arduino!
Common Pitfalls
Using String objects can cause memory fragmentation on small Arduino boards with limited RAM, leading to crashes. To avoid this, use char arrays for fixed or small strings.
Also, remember that char arrays must end with a null character '\0' to mark the end of the string.
arduino
/* Wrong way: Using String in a loop can cause memory issues */ void loop() { String temp = "Count: "; temp += String(millis()); // This creates many temporary String objects Serial.println(temp); delay(1000); } /* Better way: Use char array and snprintf */ void loop() { char temp[20]; snprintf(temp, sizeof(temp), "Count: %lu", millis()); Serial.println(temp); delay(1000); }
Quick Reference
- String: Easy to use, dynamic size, but can cause memory issues on small boards.
- char[]: Fixed size, manual management, safer for limited memory.
- Use
+=to add text toStringobjects. - Use
snprintforstrcpyforchar[]manipulation. - Always end
char[]strings with'\0'.
Key Takeaways
Use
String objects for easy text handling but be cautious on small memory boards.Use
char[] arrays for fixed or memory-critical string operations.Always terminate
char[] strings with a null character '\0'.Avoid creating many temporary
String objects in loops to prevent memory fragmentation.Use
+= to append text to String objects and snprintf for char[] formatting.