Compare Strings in Arduino



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.

Updated on: 2021-05-29T13:32:02+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements