Diti Diti - 1 year ago 86
Dart Question

How to work with char types in Dart? (Print alphabet)

I am trying to learn the Dart language, by transposing the exercices given by my school for C programming.

The very first exercice in our C pool is to write a function

that prints the alphabet in lowercase; it is forbidden to print the alphabet directly.

In POSIX C, the straightforward solution would be:

#include <unistd.h>

void print_alphabet(void)
char c;

c = 'a';
while (c <= 'z')
write(STDOUT_FILENO, &c, 1);

int main(void)
return (0);

However, as far as I know, the current version of Dart (1.1.1) does not have an easy way of dealing with characters. The farthest I came up with (for my very first version) is this:

void print_alphabet()
var c = "a".codeUnits.first;
var i = 0;

while (++i <= 26)

void main() {

Which prints the ASCII value of each character, one per line, as a string ("97" ... "122"). Not really what I intended…

I am trying to search for a proper way of doing this. But the lack of a
type like the one in C is giving me a bit of a hard time, as a beginner!

lrn lrn
Answer Source

Dart does not have character types.

To convert a code point to a string, you use the String constructor String.fromCharCode:

int c = "a".codeUnitAt(0);
int end = "z".codeUnitAt(0);
while (c <= end) {
  print(new String.fromCharCode(c));

For simple stuff like this, I'd use "print" instead of "stdout", if you don't mind the newlines.

There is also:

int char_a = 'a'.codeUnitAt(0);
print(new String.fromCharCodes(new Iterable.generate(26, (x) => char_a + x)));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download