How to Compare if string contains given word?

Hi,

I'm receiving data from an xbee, the data received is like these: "INTTO1; Amber", I want to
compare if a string is inside the received values, for example "if (XBee.read () contains" Amber ")",
If so, print me a message. But my code still does not work, how could I make it work?

This is my code:

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

void loop() {
if (XBee.available())
  { 
    Serial.write(XBee.read());

    String variable = XBee.read();
    int var = variable.indexOf("Amber");
    if (var>=0)
  {
        Serial.write("COMPLET");
  }
  }
  
  }

Regards.

Apart from losing the **S**tring, you can use strcmp() with a c-string.

Hi lastchancename,

My code still does not work, using that function is it possible that it works?

Regards.

Sorry, but i don’t have experience with xbee, but looking at your code...

Serial.write(XBee.read());
    String variable = XBee.read();

I suspect that what you’re doing is reading the most recent character (to print it): then expecting to read() it a second time... but it’s already been consumed by the print()

Just fyi, you may not realise, but read() only acquires the next character - NOT a whole word or phrase...
read() will never return “Amber” or any other multi-character string...

There are various tutorials in the forum and IDE that will help you with this... but still avoid Strings with a capital S !

It is not a good idea to use the String (capital S) class on an Arduino as it can cause memory corruption in the small memory on an Arduino. This can happen after the program has been running perfectly for some time. Just use cstrings - char arrays terminated with '\0' (NULL).

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data. There is also a parse example to illustrate how to extract numbers from the received text.

Use the strstr() function to see if a cstring is contained in another cstring.

...R