According to the manual:


Trim strips one or more whitespaces from the beginning and the end. Does it also removes tabulators and \n ?

I have the following code which works:

 while (Serial.available()) {   // something came across the serial   
      char c = (char)Serial.read();
      Command += c;
      if (c=='\n')
           Complete =true;
   if (Command.length() >0 && Complete) {

        if (Command == "LED_ON") {
               // Do stuff

Although I'm not sure that it is working because of the last if statement which says: if (Command == "LED_ON") ignores the ending \n and say ok it matched OR Command.trim() really takes off that \n.

Thank you

  • OMG, he's using String! Argh! That's evil! I suggest you learn how to do things properly and don't rely on (broken) crutches like String. hackingmajenkoblog.wordpress.com/2016/02/01/… hackingmajenkoblog.wordpress.com/2016/02/04/…
    – Majenko
    Oct 31, 2016 at 14:50
  • 1
    I would make a general comment saying that similar functions in other programming languages that do 'trim' remove all whitespace which usually includes newlines spaces tabs carriage return etc etc. Its been confirmed that this version of trim does that but newlines and tab are generally considered whitespace in most languages.
    – crowie
    Nov 1, 2016 at 9:08

2 Answers 2


Yes, \n is also removed.

The source for the trim() function is in WString.cpp.

void String::trim(void)
    if (!buffer || len == 0) return;
    char *begin = buffer;
    while (isspace(*begin)) begin++;
    char *end = buffer + len - 1;
    while (isspace(*end) && end >= begin) end--;
    len = end + 1 - begin;
    if (begin > buffer) memcpy(buffer, begin, len);
    buffer[len] = 0;

We can see it uses the isspace() function, but where's that function defined? WString.cpp only #includes WString.h, so we go there.

In WString.h, we can see it includes ctype.h. Time to go to the C++ Reference, which tells us that yes, \n is a "space" according to isspace(), so it is trimmed.

(note that isspace() is affected by localization settings. I'm not sure what the localization settings are when compiling for Arduino)


Whilst rchard2scout is quite right that trim will remove newlines, why not rearrange the code so it doesn't matter?

  char c = (char)Serial.read();
  if (c == '\n')
     Complete = true;
     Command += c;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.