length() problem

Hi, everyone. I am begginer and I have a problem in my code:
It is a code that, when typing something on the serial monitor, it writes the number of characters in the variable.
When I type, it always shows an extra value in length ().
Example: when typing and sending "1234567", it shows length () = 8 and not 7.
Would anyone know why? Thanks for the answer!

String d;


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

}

void loop() {

  if (Serial.available() > 0) {
    d = "";
    while (Serial.available() > 0) {
      //FAZ A LEITURA DA SERIAL E ARMAZENA NA VARIÁVEL LOCAL (CHAR)
      char ch = Serial.read();
      //COLOCA O RESULTADO NUMA VARIÁVEL GLOBAL (STRING)
      d += ch;
      //Serial.print(ch);
    }
    Serial.println("Length:");
    Serial.println(d.length());
  }
}

teste_string.ino (454 Bytes)

What is the line ending setting for the serial monitor?

new-line

Changing for None end-of-line, it works :slight_smile:

Whats the difference?

Thank you!

The difference is a newline character.

Got it.

Thank you so much!

It is highly recommended using String.reserve() to prevent the memory fragmentation issue

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.