How to Remove Characters from a String in Arduino?


The remove function in Arduino helps you remove one or more characters from within a string.

Syntax

myString.remove(index, count)

Here, index refers to the index from where removal has to start. Note that indexing in Arduino starts with 0. Thus, within string "Hello", 'H' is at index 0, 'e' is at index 1, and so on.

The count argument is optional, and it specifies the number of characters to remove. If you don’t specify the count, then all characters starting from index till the end of the string will be removed. If you specify count as say, 3, then 3 characters starting from index position will be removed.

Example

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();
   String s1 = "Mississippi";
   String s2 = "Mississippi";
   String s3 = "Mississippi";

   Serial.println(s1);
   Serial.println(s2);
   Serial.println(s3);
   Serial.println();

   s1.remove(3,6); //Remove 6 characters starting from position 3
   s2.remove(3); //Remove all characters starting from position 3
   s3.remove(3,1); //Remove 1 character starting from position 3

   Serial.println(s1);
   Serial.println(s2);
   Serial.println(s3);
}

void loop() {
   // put your main code here, to run repeatedly:
}

Output

The Serial Monitor output is shown below −

As you can see, the removal of characters happens exactly as described in the comments of the code.

Updated on: 29-May-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements