Help with comparing strings

My Sketch is not working as expected when I type "mensagem" in the serial.
Follows:

String stringOne, stringTwo;

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

void loop() {
   
  if (Serial.available()>0) {
    stringOne = String("mensagem");
	  stringTwo = Serial.readString();
    if (stringOne == stringTwo){
	 		Serial.print(stringTwo);
      delay(1000);
		  }
}

}

how did you configure the serial monitor (ie what does it send as a end of line?)

➜ make sure it's set to none (otherwise you'll have invisible characters in stringTwo and thus both don't match)

you could also call trim() on stringTwo before the compare, that would remove leading and trailing spaces, including the CR and LF if you have them

--

PS: as a curtesy for readers, make sure you indented the code in the IDE before copying, that's done by pressing ctrlT on a PC or cmdT on a Mac. you'll see that the code is much more readable when indented properly and { } pairs are aligned

String stringOne = "mensagem";

void setup() {
  Serial.begin(115200);
  Serial.setTimeout(30);
  Serial.println("enter text");
}

void loop() {
  if (Serial.available() > 0) {
    String stringTwo = Serial.readString();
    stringTwo.trim();
    if (stringOne == stringTwo) {
      Serial.println("This is a match!");
    } else {
      Serial.println("No cigar!");
    }
  }
}

that being said, I would encourage you to study Serial Input Basics to handle Serial input (and not use the String class)

Comparing "Strings" is a complex undertaking. The first step is to see if the length of the Strings are equal. If not, test is complete. Then next step is to compare byte to byte until either an unequal is found or the end of a string is found.
Part of debugging your code would be to print the length of each "String".

Indeed that's what the == operator does for you in the String class...

so it's not more complex than just doing == but lots happening behind the scene

Thank you very much dude!

consider

const byte PinLed = LED_BUILTIN;

String Tgl = "tgl";
String On  = "on";
String Off = "off";

void loop()
{
    if (Serial.available ()) {
	    String str = Serial.readString();
        str.trim();

        if (Tgl == str)
            digitalWrite (PinLed, ! digitalRead (PinLed));
        else if (On == str)
            digitalWrite (PinLed, HIGH);
        else if (Off == str)
            digitalWrite (PinLed, LOW);
    }
}

void setup() {
  Serial.begin(115200); 
  pinMode (PinLed, OUTPUT);
}

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