How to Trim a String in Arduino?



Sometimes, a string can contain leading or trailing whitespaces. Arduino has a trim() function that removes all these leading/trailing whitespaces from the string.

Syntax

String1.trim()

Where String1 is the string that you need to trim. Please note that this function doesn’t return anything. String1 itself is modified.

Example

The following example illustrates this −

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();

   String string1 = " Hello World! ";
   Serial.println(string1);
   string1.trim();
   Serial.println(string1);
}

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

Output

The Serial Monitor output is shown below −

As you can see, string1 was modified in place.


Advertisements