OneBite.Dev - Coding blog in a bite size

Compare Two Strings In Dart

Code snippet for how to Compare Two Strings In Dart with sample and detail explanation

Dart is a popular programming language widely used in the development of robust and scalable applications. In this article, we will take a look on how to compare two strings in Dart using the compareTo() function, highlighting a simple code snippet and providing a step-by-step explanation of how it works.

Code snippet for String Comparison in Dart

Here’s a simple code snippet that illustrates how to compare two strings in Dart.

void main() { 

  String str1 = "Hello"; 
  String str2 = "world"; 
  
  // comparing two strings
  int result = str1.compareTo(str2);

  print(result);

}

Code Explanation of String Comparison in Dart

The above code snippet shows a very basic yet essential operation which is comparing two Strings.

Now let’s break down the code:

  1. We start by declaring our main function: void main(). This is the entry point of our application.

  2. Inside this function, we define two strings: String str1 = "Hello"; and String str2 = "world";.

  3. To compare these two strings, we need to use the compareTo() function. This function is a method of the String class in Dart and it is used to compare the calling string object with specified string object. The syntax for this method is: string1.compareTo(string2). The function returns an integer: if the return value is less than 0 then string1 is less than string2, if the return value is 0 then string1 is equal to string2, and if the return value is greater than 0 then string1 is greater than string2.

  4. In our case, str1.compareTo(str2) compares “Hello” to “world”. This results in a negative integer because “H” comes before “w” in the alphabet.

  5. The print(result) statement then prints this result to the console.

That’s it! Now you know how to compare two strings in Dart. Understanding how String comparison works in Dart—or any other programming language—is crucial as it is a fundamental part of writing efficient, functional code. From sorting to setting conditions, string comparison plays a significant role in application building.

dart