Replace characters in a string in Arduino


The .replace() function in Arduino allows you to replace a character or a substring with another character/substring in Arduino.

Note: This function replaces substrings in the original string itself, and does not return a new string containing the changes.

Examples are given in the code below −

Example

void setup() {
   Serial.begin(9600);
   Serial.println();
   String s1 = "Hello World";
   Serial.println(s1);
   s1.replace('e','a');
   Serial.println(s1);
   
   s1 = "Hello World";
   s1.replace("ll","gg");
   Serial.println(s1);

   s1 = "Hello World";
   s1.replace("li","gg");
   Serial.println(s1);
}
void loop() {
   // put your main code here, to run repeatedly:
}

The Serial Monitor output is shown below −

Output

As you can see, in the last attempt, the string was unchanged. This is because the substring 'li' was not part of s1. Therefore, there was nothing to replace!

Updated on: 24-Mar-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements