String.compareTo()

Description

Compares two Strings, testing whether one comes before or after the other, or whether they're equal. The strings are compared character by character, using the ASCII values of the characters. That means, for example, that 'a' comes before 'b' but after 'A'. Numbers come before letters.

Syntax

myString.compareTo(myString2)

Parameter Values

  • myString: a variable of type String.
  • myString2: another variable of type String.

Return Values

  • a negative number: if myString comes before myString2.
  • 0: if String equals myString2.
  • a positive number: if myString comes after myString2.

Example Code

void setup() { Serial.begin(9600); String myString = "Arduino"; String myString2 = "ArduinoGetStarted.com"; int result = myString.compareTo(myString2); Serial.println(result); } void loop() { }

The result on Serial Monitor:

COM6
Send
-71
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

※ NOTES AND WARNINGS:

If the string is modified, it is highly recommended using String.reserve() to prevent the memory fragmentation issue

See Also

ARDUINO BUY RECOMMENDATION

Arduino UNO R3
Arduino Starter Kit
Disclosure: Some links in this section are Amazon affiliate links. If you make a purchase through these links, we may earn a commission at no extra cost to you.
Additionally, some links direct to products from our own brand, DIYables.

※ OUR MESSAGES