user5021612
user5021612

Reputation:

How to make simple string compare in C (Arduino)?

I new to C and I'm attempting to writte a simple code for Arduino (based on Wiring language) like this:

void loop() 
{  
  distance(cm);
  delay(200);    
}

void distance(char[3] unit) 
{
  if (unit[] == "cm") 
    Serial.println("cm");
}

Could somebody please advise me how to writte it correctly? Thanks in advance!

Upvotes: 1

Views: 90

Answers (1)

frarugi87
frarugi87

Reputation: 2880

There are several ways.

The most "basic" one is using the strcmp function:

void distance(char* unit) 
{
    if (strcmp(unit, "cm")  == 0) 
        Serial.println("cm");
}

Note that the function returns 0 if the strings are equal.

If you have fixed-length strings maybe testing every single character is faster and less resources-consuming:

void distance(char* unit) 
{
    if ((unit[0] == 'c') && (unit[1] == 'm') && (unit[2] == '\0')) 
        Serial.println("cm");
}

You can also do other things (such as iterating through the arrays if the strings can have different length).

Bye

Upvotes: 2

Related Questions