Arduino String replace(): Syntax, Examples, and Tips

How-to basics · Updated November 22, 2026

Arduino’s String.replace() method changes a String object in place: call text.replace("old", "new"); to replace every matching substring, or text.replace('a', 'b'); to replace characters. It does not return the edited text, so use it as a statement rather than assigning its result.

What String.replace() Does

The Arduino String class provides two common forms of replace(): one for a character and one for a substring. Both edit the String object on which the method is called. For example, after message.replace("error", "warning");, the changed value is still held in message.

When the search text occurs more than once, the method replaces each occurrence it finds. A useful mental model is “find this text in the current String and substitute that text,” not “create and return a separate replacement String.” This distinction explains why code such as String result = message.replace("old", "new"); is incorrect: replace() has no String return value.

The method is useful for straightforward edits to a message, command, label, or other text stored as an Arduino String. It is not a regular-expression replacement facility: a search value is treated as literal text, not a pattern.

Syntax and Overloads

The two typical overloads are:

  • text.replace(char find, char replacement); replaces occurrences of one character with another.
  • text.replace(const String& find, const String& replacement); replaces occurrences of a substring with another String.

String literals such as "ON" and "OFF" are commonly passed to the substring overload; the Arduino String implementation can construct the needed String values from them. The method’s return type is void, and it changes text. If the search value is absent, the contents remain unchanged.

For a substring search, an empty search value is not useful. Arduino String implementations generally treat an empty search as a no-op rather than repeatedly inserting replacement text. For portable, readable code, check that the value you intend to search for is nonempty before calling the method.

Basic Examples

This sketch changes all lowercase instances of temp to temperature, then prints the edited message:

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

  String message = "temp sensor: temp is 21 C";
  message.replace("temp", "temperature");

  Serial.println(message);
}

void loop() {
}

The output is temperature sensor: temperature is 21 C. The original variable is now edited; there is no separate result variable unless you make a copy first.

The character overload is handy for changing a delimiter or formatting characters:

String reading = "21.5,22.0,20.8";
reading.replace(',', ';');
Serial.println(reading);

This prints 21.5;22.0;20.8. Use single quotes for character literals such as ',', and double quotes for String values such as ",". A character replacement changes one character to one character; use the substring overload if the replacement must have a different length.

Replacing, Removing, and Preserving Text

To remove a substring, replace it with an empty String. For instance, with String code = "A-17-B";, calling code.replace("-", ""); leaves A17B. Removing a character works similarly: code.replace('-', ' '); changes each hyphen to a space rather than deleting it.

Because replacement edits the original object, copy the value first when both versions are needed. For example, declare String original = "Mode: AUTO"; and then String display = original; before replacing text in display. The copy has its own String value, so changing it does not intentionally change original. On memory-constrained boards, though, keeping multiple String values also uses more memory.

Replacement text is inserted as text, not repeatedly processed as part of the same requested substitution. If you need a sequence of transformations, make each step explicit and think about their order. For example, replacing "A" with "B" and then replacing "B" with "C" in a second call will also affect the B characters created by the first call. That may be intended, but it is different from one independent replacement.

Case Sensitivity and Matching Details

Matching is case-sensitive. Searching for "temp" does not match "Temp" or "TEMP". This commonly surprises people when editing serial commands or text received from a user, since capitalization may vary.

If the input is a known set of command words, one option is to normalize a copy before matching, while retaining the original if capitalization matters for display. Be aware that converting a whole String to lowercase or uppercase changes its contents; it does not provide a case-insensitive replacement that preserves the untouched text’s original capitalization. equalsIgnoreCase(), where available in the String API, checks equality and is not a replacement method.

The search is literal. For example, replace(".", "_") searches for a period character; the dot does not mean “any character.” Likewise, the method does not support wildcard searches, capture groups, or regular expressions. If the desired match depends on a more complex rule, scan the characters yourself or use a parsing approach designed for that input.

Using replace() with Serial Input

A frequent application is cleaning up a line received over Serial. This example reads through a newline, removes a carriage return if one remains, and changes commas to spaces:

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

void loop() {
  if (Serial.available() > 0) {
    String line = Serial.readStringUntil('\n');
    line.replace("\r", "");
    line.replace(',', ' ');
    Serial.println(line);
  }
}

Serial data often uses a line ending that includes a carriage return and a newline. readStringUntil('\n') stops at the newline, while removing "\r" handles a carriage return included in the returned text. The exact input format depends on the sending device, so inspect what arrives before adding cleanup rules. Avoid replacing characters blindly if they carry meaning in the data, such as commas separating fields that your parser still needs.

readStringUntil() waits for its terminator or a Stream timeout. For responsive programs, consider whether waiting for a complete line is acceptable; a nonblocking character-by-character parser can be more suitable when the sketch must keep servicing other tasks.

Common Problems and Memory Considerations

  • Expecting a return value: call text.replace(...); and then use text. Do not put the call on the right side of an assignment.
  • Searching with the wrong capitalization: matching is case-sensitive, so confirm the incoming text and search value have the same case.
  • Using the wrong quote type: a single character uses single quotes, while a String literal uses double quotes.
  • Calling it on a character array: a plain char[] is not an Arduino String object and has no replace() member.

Arduino String objects manage memory dynamically. A replacement that makes text longer may require additional storage, and repeated String construction or editing can be a concern on boards with very little RAM, particularly small AVR-based boards. The exact memory capacity and behavior depend on the board and core, so avoid assuming that a sketch suitable for a board with ample RAM will fit on every Arduino-compatible device.

For short, bounded messages, String can be convenient and readable. For long-running or memory-tight programs, keep inputs within known limits, avoid building many temporary Strings in a loop, and check available memory practices for the particular board. A fixed-size character buffer can make memory use more predictable, but it requires careful bounds checking; using one is not automatically safer if incoming data can exceed its capacity.

String.replace() Compared with Character Arrays

Arduino’s String object and a C-style character array are different types. With a String, the method call is direct: text.replace("old", "new");. With a buffer such as char text[32], there is no member method with that syntax. You need to write or use a separate function that searches and edits the buffer, while ensuring the new text fits and the result remains null-terminated.

For example, replacing a two-character word with a much longer phrase in a fixed buffer may exceed the available capacity. A String can grow dynamically when memory permits, whereas a fixed buffer cannot. Conversely, a fixed buffer’s reserved capacity is explicit and can be useful in tightly controlled embedded applications. Choose based on the board’s RAM, the maximum input size, and how much complexity is acceptable—not on the assumption that one approach is always best.

Also distinguish Arduino’s String from a null-terminated C string. A variable declared as String name uses the Arduino class. A variable declared as char name[] uses a character array. Calling a function with the same name in another language or library does not make its behavior applicable to Arduino’s String class.

Frequently Asked Questions

Does Arduino String.replace() replace every match?
Yes, the standard Arduino String method replaces occurrences throughout the String, not just the first match. The operation edits the object you call it on.

Does replace() return the new String?
No. It returns no value. Call the method on a String variable, then read or print that variable to use the changed text.

How do I remove a word or character from an Arduino String?
Replace the target with an empty String, as in text.replace("remove", "");. For a character, use the substring form or replace it with another character; the character overload itself replaces rather than deletes.

Is Arduino String.replace() case-insensitive?
No. The search is case-sensitive, so "ON" and "on" are different matches. Normalize the text or implement a case-insensitive scan if that behavior is required.

Can I use replace() on a char array?
Not as a member call. The method belongs to Arduino’s String class. A char[] needs a separate buffer-editing routine that accounts for its capacity and terminating null character.

Choosing the Right Approach

Use String.replace() when the text is already held in an Arduino String and the edit is a simple literal substitution. Check the exact case and search value, remember that the original object changes, and verify the result with a print or comparison while debugging. For complex patterns, structured data, or strict memory limits, use a parser or a carefully bounded character-buffer routine instead.

The central rule is simple: replace() is an in-place editing method, not a function that produces a replacement String. Once that is clear, its character and substring forms are easy to apply without confusing the Arduino API with similarly named operations in other languages.

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.