Arduino String Functions: Methods, Examples, and Tips

Formulas & functions · Updated November 22, 2026

Arduino string functions are methods for working with text stored in the Arduino String class: for example, length() measures a string, indexOf() searches it, and substring() extracts part of it. These methods are useful for tasks such as interpreting Serial Monitor commands, but Arduino also supports C-style character arrays, which use a different set of functions.

What “string functions” means in Arduino

In Arduino sketches, “string” can refer to two different things. The capitalized String is an Arduino class that represents text as an object. A lowercase C string is an array of characters ending with a null character, written '\0'. The two forms can both hold text, but their functions and memory behavior are different.

Most Arduino String operations are called with dot notation. For example, if message is a String, you can call message.length() or message.toUpperCase(). C string functions, by contrast, are commonly called by passing a character-array address, as with strlen(buffer).

For small sketches and straightforward text handling, the String class is often easier to read. For fixed-size data, memory-constrained boards, or code that interacts with C libraries, character arrays can offer more explicit control. Neither choice is automatically right for every project.

Common Arduino String methods

The most useful methods cover measuring, comparing, searching, extracting, editing, and converting text. The following examples assume a variable named text is a String.

  • length() returns the number of characters. It does not include a C-style null terminator as part of the text.
  • charAt(index) reads the character at a zero-based position. The square-bracket form, such as text[0], is also commonly used to access a character.
  • equals(other) tests whether the contents match; equalsIgnoreCase(other) compares without distinguishing letter case.
  • startsWith(prefix) and endsWith(suffix) test the beginning and end of the text.
  • indexOf(value) finds the first occurrence of a character or substring. It returns -1 if there is no match. lastIndexOf(value) searches from the end.
  • substring(from, to) extracts characters from index from up to, but not including, index to. With one index, it extracts from that position to the end.
  • trim() removes whitespace from the beginning and end. It changes the existing String rather than returning a separate trimmed copy.
  • toLowerCase() and toUpperCase() change the letters’ case in the existing string.
  • replace(find, replacement) replaces matching text, while remove(index, count) deletes characters starting at a position.
  • toInt() and toFloat() convert numeric text to a number. toInt() returns a long; neither method is a full input-validation check.

Many methods modify the object, while others return a result. For example, trim() changes the text you call it on, whereas substring() produces a new String. Check whether a method mutates its receiver before assuming the original value remains unchanged.

Examples of searching, extracting, and changing text

This short example shows several operations together. Indexes begin at zero, so the first character is at index 0. In substring(0, 3), the second index is the stopping point and is not included.

String text = "Arduino sensor: 23";

int colon = text.indexOf(':');
String label = text.substring(0, colon);
String valueText = text.substring(colon + 1);
valueText.trim();
long value = valueText.toInt();

Serial.println(label);      // Arduino sensor
Serial.println(value);      // 23

text.replace("sensor", "reading");
text.toUpperCase();
Serial.println(text);        // ARDUINO READING: 23

The example assumes the colon exists. If input is variable, check the search result before using it as a substring index: indexOf() returns -1 when the character is absent. Also note that converting text with toInt() does not prove that the entire input was a valid number. Invalid or nonnumeric input can produce zero, which is indistinguishable from a legitimate numeric zero without separate validation.

Reading and interpreting Serial input

String methods are often used to parse commands received over the serial port. A line-oriented sketch can read through the newline character, remove surrounding whitespace, and then test the command:

void setup() {
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    String line = Serial.readStringUntil('\n');
    line.trim();

    if (line.equalsIgnoreCase("START")) {
      Serial.println("Starting");
    } else if (line.startsWith("LED=")) {
      String valueText = line.substring(4);
      long level = valueText.toInt();
      Serial.println(level);
    }
  }
}

readStringUntil('\n') waits for a newline or for the stream timeout, so it can pause the rest of the sketch while waiting. The Stream timeout is one second by default in the Arduino API; it can be changed with Serial.setTimeout(). Serial Monitor line-ending settings matter: sending a newline works with this example, and trim() also removes a carriage return that may accompany it. For applications that must respond continuously, consider reading available characters incrementally rather than waiting for a complete line.

The command example accepts strings beginning with LED=, but it does not validate that the rest is a permitted numeric value or range. A real device should check the input before using it to control hardware. For example, a brightness command might need to reject values outside the range supported by the chosen output.

String objects versus C-style character arrays

A C string is stored as characters followed by a terminating '\0'. The standard C library provides functions such as strlen() for measuring, strcmp() for comparing, strcpy() for copying, and strstr() for searching. These functions work with character arrays, not directly with Arduino String objects. The required declarations are generally available through standard headers such as <string.h>.

For example, a fixed-size buffer can make its maximum storage visible in the code: char command[16]; can hold at most 15 text characters plus the null terminator. That limit means a program must avoid copying longer input into the buffer without checking its size. With a String, the text can grow dynamically instead, which is convenient but does not eliminate the board’s memory limits.

You can convert between the forms when needed. The String methods c_str() and toCharArray() provide access to character data or copy it into a buffer. A pointer returned by c_str() refers to storage owned by the String; do not assume it remains valid after changing or destroying that object. When copying into a fixed buffer, make sure it is large enough for the text and its terminating null character.

Choose based on the job: String methods are usually clearer for occasional command parsing and concatenation, while fixed buffers can be a better fit when memory use must be predictable. A library’s interface may also determine which representation it expects.

Memory use and performance considerations

A String stores text in dynamically allocated memory. As the text grows, the implementation may need to allocate or resize storage. On boards with limited RAM, repeated creation and alteration of many strings can contribute to memory pressure. On some small-memory systems, allocation patterns can also fragment available memory, making a large continuous block harder to obtain even if some memory remains free.

This is not a reason to avoid String in every sketch. The risk depends on the board, core, available RAM, and how the program uses text. A short sketch that handles a few brief commands may be perfectly practical. A long-running program that repeatedly builds changing messages or stores large incoming lines deserves more careful memory planning.

Useful habits include:

  • Keep expected input lengths bounded, and reject or truncate data that exceeds the design limit.
  • Avoid repeatedly joining many small pieces inside a tight loop when a fixed buffer or one planned construction would do.
  • Where supported by the board’s Arduino core, use reserve(size) to request capacity in advance when a string’s likely size is known. This can reduce reallocations, but it does not create more RAM or guarantee that an allocation will succeed.
  • Test the sketch on the actual target board, especially if it runs continuously or uses several libraries that also allocate memory.

Common mistakes and misconceptions

A frequent error is treating a method as if it were a free-standing function. Write text.length(), not length(text), when text is an Arduino String. Conversely, strlen(buffer) is a C function for a null-terminated character array, not a replacement method for a String.

Another common source of bugs is forgetting that indexes start at zero or that the end index in substring(from, to) is exclusive. Searching for a delimiter and immediately using its result without checking for -1 can also produce an unintended range.

Finally, a conversion method is not the same thing as input validation. If a command must contain only digits, or must fall within a safe range, check those conditions explicitly before acting on the converted value. This is particularly important when text controls a motor, heater, relay, or other physical output.

Frequently Asked Questions

What is the difference between String and string in Arduino?
The capitalized String is an Arduino class with methods such as length() and indexOf(). A lowercase C string is a null-terminated character array, typically handled with functions such as strlen() and strcmp().

How do I check whether an Arduino String contains text?
Call indexOf() with the character or substring you are looking for, then check that the result is not -1. For a test at the beginning or end, use startsWith() or endsWith().

How do I compare two Arduino strings without case sensitivity?
Use equalsIgnoreCase(), for example first.equalsIgnoreCase(second). This compares the text without distinguishing uppercase and lowercase letters.

Does trim() return a trimmed String?
trim() changes the String object it is called on; it is not a separate result to assign. Call line.trim(); and then use line.

Why does toInt() return zero?
The input may be nonnumeric, empty, or otherwise unsuitable for conversion, and zero is also a valid number. Check the original text and validate the allowed format and range if the distinction matters.

Should I use String or char arrays?
Use whichever fits the project’s memory constraints and interfaces. String is convenient for many small parsing tasks; fixed-size character arrays make storage limits explicit but require careful bounds and null-termination handling.

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.