Arduino String Functions: Methods, Examples, and Tips

Formulas & functions · Updated November 22, 2026

Arduino String functions are methods and operators for storing, joining, searching, editing, and converting text in an Arduino sketch. The capitalized String class is convenient for changing text at runtime; for small or memory-constrained projects, fixed-size C-style character arrays are often a more predictable alternative.

What Arduino means by String

Arduino sketches can work with text in two common forms. A String is an object provided by the Arduino core, with methods such as substring() and indexOf(). A C-style string is an array of characters ending in a null character, written as char text[]. They are related, but their functions and memory behavior are different.

Capitalization matters: String names the Arduino class, while string is not the same type. A quoted text literal such as "ready" can be used to initialize a String or passed to many String methods. The exact implementation is supplied by the board’s Arduino core, so details can vary among AVR, SAMD, ESP32, and other boards. Consult the documentation for the core in use if a method’s return type or behavior matters to a particular application.

String objects are useful when text length changes, such as when assembling a message from sensor readings or handling a line received over Serial. They do not replace every text tool in C or C++: functions such as strlen() and strcpy() operate on null-terminated character arrays, not directly on String objects.

Creating and combining String objects

A String can be initialized with text, or created empty and filled later. The + and += operators join String values and compatible text or character values. The concat() method also appends content. For example:

String message = "Temperature: ";
message += String(23);
message += " C";
Serial.println(message);

This prints Temperature: 23 C. Converting the number to a String explicitly makes the intention clear; Arduino also supports appending many numeric values directly. When the same String will grow repeatedly, reserve() can request storage capacity in advance:

String line;
line.reserve(80);

Reserving space can reduce repeated reallocations, but it does not make the String unlimited or guarantee that memory is available. Choose a realistic capacity rather than reserving a very large buffer without need. A failed allocation or a String that grows beyond available memory can still cause problems.

Common String methods and what they do

String methods are called on an object, using a dot between its name and the method. The most useful groups are inspection, comparison, searching, editing, and conversion. Check the Arduino reference for the target core when relying on a less commonly used method.

  • length() reports the number of characters in the String. It does not count a C-string terminator, because a String object is not itself a null-terminated array exposed for ordinary indexing.
  • charAt(index) reads a character at a zero-based position; setCharAt(index, character) changes one. Check the length before using an index that comes from input.
  • equals(other) checks whether two strings match, while equalsIgnoreCase(other) compares without treating letter case as significant. compareTo(other) gives a comparison result rather than a simple true-or-false answer.
  • startsWith(prefix) and endsWith(suffix) test the beginning and end. Some Arduino cores also support an offset argument for startsWith().
  • indexOf(value) finds the first occurrence; lastIndexOf(value) finds the last. A search that finds nothing returns -1, so test for that before using the result as an index.
  • substring(from, to) returns a portion of a String. The starting position is included and the ending position marks where the selection stops. The one-argument form returns from the given position to the end.
  • replace(find, replacement) substitutes matching text, and remove(index, count) deletes characters from a position. trim() removes whitespace at the start and end, not whitespace in the middle.
  • toLowerCase() and toUpperCase() change the String’s letter case. toInt() and toFloat() convert text to numeric values.

Many methods that edit a String change the object on which they are called. For example, call input.trim(); when you want to remove surrounding whitespace from input itself. By contrast, substring() produces a String result, which you can store in a separate variable.

Searching, extracting, and editing text

Consider a Serial command in the form mode=auto. A sketch can locate the separator, then take the text on either side. Because indexes start at zero, the character immediately after the equals sign is at separator + 1.

String command = "mode=auto";
int separator = command.indexOf('=');

if (separator != -1) {
  String key = command.substring(0, separator);
  String value = command.substring(separator + 1);
  Serial.println(key);
  Serial.println(value);
}

The output is mode followed by auto. Checking for -1 is important: without the check, a missing separator could lead to incorrect parsing or an invalid position. For commands with multiple separators, search again from an offset if the core provides the relevant overload, or walk through the input deliberately.

To edit a String, use methods that make the desired change explicit. For instance, command.replace("auto", "manual"); changes the matching text in command. Use startsWith() when a command is recognized by its prefix, and equalsIgnoreCase() when a command should accept either uppercase or lowercase letters. Case-insensitive comparison is not the same as trimming: input such as " AUTO " still has surrounding spaces, so call trim() if those should be ignored.

Converting text and handling Serial input

Text received over Serial often includes a line ending or extra spaces. A basic approach is to read a line, normalize it, then compare or convert it. The Serial method readStringUntil() reads up to a chosen character and returns a String; it waits according to the stream timeout if the terminator does not arrive. For example:

String reading = Serial.readStringUntil('\n');
reading.trim();
long value = reading.toInt();

toInt() returns a long, not an int. toFloat() returns a floating-point value. These convenience conversions do not provide a separate success flag that proves the entire input was a valid number. A malformed or empty value can therefore be mistaken for zero. If distinguishing invalid input from the valid number zero matters, validate the characters or use a parsing approach that reports errors.

Serial input also needs a size and timing plan. A line may be longer than expected, and a blocking read can pause the rest of a sketch while waiting for its terminator or timeout. For a responsive device, consider reading available bytes incrementally into a bounded buffer and processing the line when it is complete. The right approach depends on how the device should behave while input is incomplete.

String and C-style strings: choosing between them

String is often the easiest choice for beginners and for text whose length varies. Methods make common operations readable, and the class handles its own storage. C-style strings use a character array with a terminating '\0'; standard C functions such as strcmp(), strchr(), and strstr() can search or compare them.

  • Choose String when concise code and convenient editing matter, and the board has enough memory for the expected text and temporary allocations.
  • Choose a fixed-size character array when maximum input length is known and predictable memory use is important. Keep room for the terminating null character.
  • Use the form required by a library’s interface. Some APIs accept a String; others need a const char* or a writable character buffer.

String objects can expose their character data with methods such as c_str(), while toCharArray() copies text into a caller-provided buffer. The buffer must be large enough for the copied characters and the terminator. The returned pointer from c_str() is associated with the String’s storage; do not assume it remains valid after changing or destroying that String. For a copied buffer, ensure its size is correct and check what portion of the source is copied.

Moving between these forms does not automatically make the data safe. Copying into a buffer that is too small can truncate text or lead to errors if the buffer is mishandled. Conversely, building many temporary String objects can create unnecessary memory activity. Match the representation to the program’s constraints instead of treating one form as universally best.

Memory use and common problems

String objects use dynamically managed memory. On boards with limited RAM, repeatedly creating, enlarging, and discarding Strings can contribute to heap fragmentation: free memory may become divided into small regions, making a larger allocation difficult even when the total free memory seems adequate. This is a risk to assess, not proof that every String-based sketch will fail. Board architecture, core implementation, available memory, and the sketch’s allocation pattern all matter.

Several habits help keep text handling reliable:

  • Set a reasonable maximum input length and reject or safely handle longer input.
  • Use reserve() when a String has a predictable final capacity and grows repeatedly.
  • Avoid building a new long message in every pass through a fast loop if a fixed buffer or reused object would suit the task.
  • Check search results before treating them as valid indexes, and check input length before reading a character at a position.
  • Test empty input, missing delimiters, whitespace, unusually long lines, and invalid numbers—not just the expected command.

A frequent misconception is that String.toInt() is a strict validator. It is a conversion convenience, not a complete input-validation system. Another is that trim() removes every space; it only removes whitespace at the ends. Finally, length() gives a character count, not the size of the object in bytes or the memory occupied by its allocation.

Frequently Asked Questions

What is the difference between String and string in Arduino?
The Arduino String class has a capital S and provides object methods for text. A lowercase string is not an interchangeable name for that class; C-style text is usually stored in a character array such as char text[].

How do I check whether an Arduino String contains text?
Use indexOf() and compare the result with -1. For example, message.indexOf("error") != -1 is true when that text occurs in message.

How do I compare two Arduino Strings?
Use equals() for a case-sensitive comparison, or equalsIgnoreCase() when letter case should not matter. Do not confuse equality with checking whether one String contains another; use indexOf() for a search.

Does trim() remove spaces inside a String?
No. It removes whitespace at the beginning and end. For example, trimming " motor on " gives "motor on"; the space between the words remains.

Is Arduino String bad for memory?
Not automatically. It is convenient, but dynamic allocation can be a concern on memory-limited boards, especially when Strings repeatedly grow and shrink. For bounded input, a carefully sized character buffer may offer more predictable memory use.

Why does toInt() return zero for my input?
The text may be empty or may not begin with a usable number. Since toInt() does not by itself report whether conversion succeeded, inspect and validate the input before relying on the result when zero is meaningful.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

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

Spotted an error in this guide? Let us know.