Arduino String Data Type: How It Works and When to Use It

How-to basics · Updated November 22, 2026

Arduino’s String data type is a class for storing and working with text, such as words, messages, and values received over Serial. It is convenient for many sketches, but it is not the same as a C++ character array, and on memory-limited boards its dynamic memory use deserves attention.

What Arduino means by String

String—with a capital S—is an Arduino core class, not a primitive type built into the C++ language. It represents a sequence of characters and provides operations such as joining text, finding a substring, checking its length, and converting numeric text. Most Arduino sketches can use it directly because the sketch build process includes the Arduino core declarations. In other C++ files or non-Arduino projects, the relevant core header may need to be included explicitly.

A String can hold text known at compile time or text assembled while the program runs. For example, it can store a device name, build a status message from a sensor reading, or hold a command entered through the serial monitor. The class is part of the Arduino programming environment, but its implementation details can vary between board cores. The common interface is familiar across many boards; it is still sensible to check the documentation for the particular core when relying on less common behavior.

The capitalization matters in code: String refers to the Arduino class, while string by itself is not the same type. In standard C++, std::string is a separate class from the C++ standard library. It is not simply another spelling for Arduino’s String, and whether it is available or appropriate depends on the toolchain and board.

How a String stores and handles text

Conceptually, a String contains characters in order and keeps track of how many characters it contains. You can ask for its length or access a character by position. Positions start at zero, so the first character is at index 0. Arduino’s class also manages the storage needed as text is added or changed; this is why a String can grow without the programmer choosing a fixed array size in advance.

That convenience generally involves dynamic memory: storage can be obtained and released while the program runs. The exact allocation strategy depends on the core and implementation, but the practical distinction is important on boards with limited RAM. A String variable has management overhead in addition to the text it holds, and changing its size may require memory operations. On boards with more available RAM, this is often an easy tradeoff. On a small board running for long periods, repeated growth and replacement of strings can make memory use harder to predict.

Strings are not automatically a way to store text permanently. A value created in a sketch is normally held in RAM while the program runs. If a project needs configuration or records to survive a reset or power loss, it needs an appropriate persistent-storage method, such as EEPROM emulation or a filesystem supported by that board. The details are board-specific.

Declaring, joining, and displaying Strings

A String can be initialized from a text literal, assigned another value, or built from several pieces. The following sketch fragment shows typical operations:

String deviceName = "Garden sensor";
String status = "Ready";

void setup() {
  Serial.begin(9600);
  status = deviceName + ": " + status;
  Serial.println(status);
}

void loop() {
}

The plus operator joins text, while assignment replaces the existing value. The += operator can append a piece to an existing String, as in status += " online";. Numeric values can also be converted and joined, although the printed representation of a floating-point value may need formatting if a particular number of decimal places matters. For example, String(temperature, 1) formats a floating-point value to one decimal place on Arduino cores that provide that constructor.

For a short status message, joining text this way is usually clear and readable. If code repeatedly appends small pieces inside a fast loop, however, consider the frequency of updates and the available RAM. It may be better to build the message only when it is needed, reuse a reserved String, or use a fixed character buffer when the maximum message size is known.

Useful String methods

The Arduino String interface includes methods for common text tasks. These examples describe widely used operations; check the board core’s reference if a method behaves differently in a particular environment.

  • length() reports the number of characters in the String.
  • charAt(index) returns the character at a position, and substring(start, end) extracts a portion. The substring start is included and its end position is excluded.
  • indexOf(value) searches for a character or text and returns its position, or a negative result when it is not found.
  • startsWith(prefix) checks whether the text begins with a given prefix.
  • trim() removes whitespace at the beginning and end, which is useful for input that may include spaces or line endings.
  • toInt() and related conversion methods interpret text as a number. Validate input separately: a failed or unsuitable conversion can be mistaken for a legitimate numeric value, especially zero.
  • reserve(size) requests capacity for a planned amount of text. It can reduce repeated storage changes when the expected size is known, but does not make a String unlimited or eliminate all memory concerns.

When passing text to a function that expects a C-style string, c_str() provides a pointer to a null-terminated character representation. Treat that pointer as temporary: changing or destroying the String can invalidate it. Do not keep the pointer for later use unless the lifetime and stability of the underlying data are guaranteed.

Memory use and reliability on small boards

Memory is the main reason experienced Arduino programmers sometimes recommend avoiding String objects. Many classic AVR boards, including the Uno family, have far less RAM than a desktop computer. A sketch may appear to work during a brief test and still fail after extended operation if it repeatedly creates, lengthens, and discards dynamically allocated text. Depending on the core and allocation pattern, heap fragmentation can make it difficult to find a sufficiently large continuous block even when some memory remains free. This is a risk, not a guarantee that every use of String will fail.

Practical ways to manage the risk include:

  • Keep messages short and avoid constructing new text unnecessarily in every pass through loop().
  • If the likely maximum size is known, call reserve() early and reuse the String rather than repeatedly replacing it with differently sized values.
  • Test the complete sketch for a long period and under realistic input, not just with one short message.
  • Use a fixed-size character array when the maximum length is known and predictable, while checking every write so the array cannot overflow.
  • On boards with more RAM, still avoid unbounded input and needless allocation; extra memory reduces pressure but does not excuse incorrect bounds or parsing.

Fixed buffers are not automatically safer or simpler. A buffer that is too small can truncate data or cause memory corruption if code writes beyond its end. Choose a capacity that includes space for the terminating null character, and use bounded operations. The right choice is a balance between predictable storage and convenient text handling.

String compared with char arrays and C strings

A C-style string is a sequence of characters in an array that ends with a null character, written '\0'. For example, char label[] = "ready"; stores the letters plus the terminating null character. Unlike an Arduino String, the array has a fixed capacity determined when it is declared. The programmer is responsible for ensuring that copied or appended text fits.

Use String when readable operations and variable-length text make the sketch simpler, especially on boards with enough RAM and when text changes are moderate. Use a character array when a fixed maximum size is known, predictable memory use matters, or an API specifically expects a C string. Arduino libraries commonly accept either type in some interfaces, but not all; read the function signature rather than assuming they are interchangeable.

For example, Serial.println(label) can print a character array, and Serial.println(status) can print an Arduino String. But a function accepting char* does not automatically accept a String object. In some cases you can pass status.c_str() if the function only needs the characters temporarily and does not modify or retain the pointer. If it keeps the pointer, copy the data into storage with a suitable lifetime.

Reading and parsing Serial input

Strings are often used to collect commands from the Serial Monitor. A simple approach is Serial.readStringUntil('\n'), which reads characters until a newline arrives or the Stream timeout occurs, then returns the collected text as a String. Because this call can wait for input or a timeout, it may pause other work in the sketch. That can be a problem for timing-sensitive tasks or code that must respond to sensors continuously.

After reading, trim line-ending whitespace before comparing a command. Serial Monitor line-ending settings can send no ending, a newline, a carriage return, or both, so the selected setting affects what the program receives. For a small command interface, a careful sketch might follow this sequence:

  1. Read one complete line, or collect characters without blocking if the program needs to remain responsive.
  2. Remove unwanted leading or trailing whitespace when appropriate.
  3. Check that the command is within an acceptable length and matches an expected command.
  4. Validate numeric text and its allowed range before using the converted value.

Do not assume that input is valid just because it arrived as a String. A command can be misspelled, too long, or contain unexpected characters. If an application must handle arbitrarily long input safely, it needs a defined maximum or a deliberate streaming parser rather than unbounded accumulation.

Choosing the right approach

There is no universal rule that Arduino String is either always good or always bad. Consider the board’s RAM, how often text is modified, the largest possible input, and how long the sketch must run without restarting. For a small interactive project that displays occasional messages, String can make code straightforward. For a memory-constrained device that continuously parses changing input, fixed buffers or a carefully designed parser may offer more predictable behavior.

Also consider the rest of the program: libraries may already use Strings, character arrays, or other representations. Converting back and forth can add complexity and allocations. Match the type expected by the library where practical, document buffer sizes, and test edge cases such as empty input and maximum-length commands. If memory becomes a concern, measure the whole application and simplify its actual allocation patterns rather than changing every String blindly.

Frequently Asked Questions

Is String a built-in Arduino data type?
No. It is a class supplied by the Arduino core, built on C++. It feels like a convenient text type, but it is distinct from C++ primitive types such as int and from the standard-library std::string.

Should I avoid String on an Arduino Uno?
Not categorically. Short, modest uses can be fine, but the Uno’s limited RAM makes repeated dynamic changes worth considering. For long-running code that continually assembles variable-length text, a bounded character buffer may provide more predictable memory use.

What is the difference between String and string?
Arduino’s class is spelled String with a capital S. Lowercase string is not an alias for it. std::string is another, separate C++ class.

How do I compare two Arduino Strings?
Use equality operators such as == for an exact, case-sensitive comparison. If text may contain extra whitespace, trim it first; if letter case should not matter, normalize or compare it using an explicit case-insensitive approach supported by the core.

Can an Arduino String store numbers?
It stores characters, not a numeric value with arithmetic semantics. You can convert a number to text for display, or parse numeric text into an integer or floating-point value. Validate the input and range before using the converted result.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.