String comparisons in Arduino

ArduinoHardwareSoftware & Coding

The same operators that are used for comparing integers like <, >, >=, <=, ==, != can also be used for comparing strings. Note that string comparisons are case-sensitive and depend on the ASCII order of characters. Thus, as per the ASCII table, 'A' comes before 'a'. Therefore 'a' > 'A'.

Example

Take a look at the following example.

void setup() {
   Serial.begin(9600);
   Serial.println();
   String s1 = "Hello";
   String s2 = "hello";
   String s3 = "100";
   String s4 = "90";
   if (s1 > s2) {
      Serial.println("s1 is greater than s2");
   } else if(s2 > s1) {
      Serial.println("s2 is greater than s1");
   }
   if (s3 > s4) {
      Serial.println("s3 is greater than s4");
   } else if(s4 > s3) {
      Serial.println("s4 is greater than s3");
   }
}
void loop() {
}

Output

The Serial Monitor output is shown below −

As you can see, s2 is greater than s1, because 'h' has a higher decimal equivalent in ASCII system than 'H'. Similarly, s4 is greater than s3, because '9' comes after '1' in the ASCII system.

It also shows that the comparison happens character by character. The first character of one string is compared to the first character of the other, and so on. While integer 90 is less than integer 100, string "90" is greater than string "100".

raja
Published on 24-Jul-2021 14:11:06
Advertisements