How to compare string with char[]?

In my program there is a point where I’d like to compare if obj and the value of myNetsData[5].code are the same, but I get the next error.

typedef struct{
    uint8_t position;
    String code;
    String name;
} NETdata;

NETdata myNetsData[12];
char obj[20];

if(obj == myNetsData[5].code){
 strlcpy(obj, &response[tok[e + 2].start], (tok[e + 2].end - tok[e + 2].start + 1));
 myNetsData[i].likes = strtol(obj,&ptrEnd,10);
}

ERROR.

error: no match for 'operator==' in 'obj == myNetsData[((int)i)].NETdata::code' 

How could I compare these two variables without changing dramatically the format type of them?

Give this a try:

#include "application.h"

String string1 = "First";
char obj[20] = "First";

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while(!Serial.available()) SPARK_WLAN_Loop();
  
  // send an intro:
  Serial.println("Comparing Strings\n");
  
  if(string1.equals("First")) {
    Serial.println("\n\nMatch 1!");
  }
  
  String string2 = String("First");
  if(string1.equals(string2)) {
    Serial.println("\n\nMatch 2!");
  }
  
  String string3 = String(obj);
  if(string1.equals(string3)) {
    Serial.println("\n\nMatch 3!");
  }
  
  if(string1.equals(obj)) {
    Serial.println("\n\nMatch 4!");
  }
}

void loop() {
  // Do nothing...
}

http://arduino.cc/en/Reference/StringObject

I always forget about String.equals(). Just to be safe, I always like to store the char value in another String object, trim that new String using String.trim(), and then upper-case it using String.toUpperCase() for a case “insensitive” compare.

I keep referring back to my “function router” to remind myself how to do it.

int fnRouter(String command) {
    command.trim();
    command.toUpperCase();

    if(command.equals("SECONDS"))
        return millis()/1000;

    ...

.trim() is great when you’re not sure where your data is coming from, but if you know… then you can speed it up by just doing the .equals() comparison. Also if you are not sure about the case of your data, you can use

if (string1.equalsIgnoreCase(string2)) {
  // is string1 equal to string2 ignoring case?
}
1 Like

Fantastic! Thanks @BDub and @wgbartley! I didn’t know .equals before and works perfect.

1 Like