Compare Strings in Arduino

ArduinoArduino BoardsArduino IDEArduino Programming Language

Arduino has an inbuilt compareTo() function that helps compare which string comes before another. Very crudely, you can think of it as this: if you are given two strings, which one will come first in a dictionary.

Syntax

String1.compareTo(String2)

Where String1 and String2 are the two strings to be compared. This function returns an integer. Here’s the interpretation of the value of the integer −

  • Negative − String1 comes before String2

  • 0 − String1 and String2 are equal

  • Positive − String2 comes before String1

Please note that this function is case sensitive. So ‘A’ comes before ‘a’ and ‘B’ comes before ‘a’. But ‘a’ comes before ‘b’. Also, numbers come before letters. Basically, if a character’s ASCII value is higher than another, then the higher character comes later in the dictionary. And compareTo() function compares the strings character by character.

Example

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();

   String s1 = "Book";
   String s2 = "books";
   String s3 = "library";

   if(s1.compareTo(s2) < 0){
      Serial.println("s1 before s2");
   }

   if(s2.compareTo(s3) < 0){
      Serial.println("s2 before s3");
   }

   if(s3.compareTo(s1) < 0){
      Serial.println("s3 before s1");
   }
}

void loop() {
   // put your main code here, to run repeatedly:
}

Output

The Serial Monitor output is shown below −

As you can see, the function works exactly as described.

raja
Published on 29-May-2021 13:21:50
Advertisements