Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare two characters in Dart?

Tags:

dart

I want to compare two characters. Something like this:

if ('a' > 'b') 

However, the above code is comparing two strings.

How do I do this in Dart?

like image 424
Seth Ladd Avatar asked Dec 22 '13 19:12

Seth Ladd


People also ask

How do you compare the elements of a list in darts?

How do you compare two lists in darts? Check if two Lists are Equal Element Wise We shall write a function areListsEqual() to check if the given two lists are equal element by element. As a pre-requisite, we check if both the given variables are lists, and then compare their lengths. list1 and list2 are equal.

How do you find the equality of two strings in darts?

We can also check whether two strings are equal by == operator. It compares every element of the first string with every element of the second string.

How do you compare string with case insensitivity in darts?

First convert both of the strings to lowercase and then compare them both. Use toLowerCase() function for both of the strings. Save this answer.

How do you compare in flutter?

Example 1 — Compare 2 students without overriding operator == : * The equality operator. * only if `this` and [other] are the same object. external bool operator ==(other);


2 Answers

String in Dart implements the Comparable interface. You can use compareTo to compare them.

String a = 'a';
String b = 'b';
String c = 'a';

print('value: ${a.compareTo(b)}');     // prints "value: -1"
print('value: ${a.compareTo(c)}');     // prints "value: 0"
print('value: ${b.compareTo(a)}');     // prints "value: 1"
like image 128
user1506104 Avatar answered Oct 11 '22 01:10

user1506104


Dart doesn't have a 'char' or 'character' type. You can get the UTF-16 character code from any point in a string, and compare that.

Use codeUnitAt to get the actual character code from a string.

if ('a'.codeUnitAt(0) > 'b'.codeUnitAt(0))

See the codeUnitAt docs: https://api.dartlang.org/docs/channels/stable/latest/dart_core/String.html#codeUnitAt

like image 29
Seth Ladd Avatar answered Oct 11 '22 01:10

Seth Ladd