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

I am trying to learn Dart language by transferring the exercises my school taught to C programming.

The first exercise in our C pool is to write the print_alphabet() function, which prints the lower case alphabet; It is forbidden to print the alphabet directly.

In POSIX C, a simple solution would be:

 #include <unistd.h> void print_alphabet(void) { char c; c = 'a'; while (c <= 'z') { write(STDOUT_FILENO, &c, 1); c++; } } int main(void) { print_alphabet(); return (0); } 

However, as far as I know, in the current version of Dart (1.1.1) there is no easy way to deal with characters. The farthest I came up with (for my first version):

 void print_alphabet() { var c = "a".codeUnits.first; var i = 0; while (++i <= 26) { print(c.toString()); c++; } } void main() { print_alphabet(); } 

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

I am trying to find a suitable way to do this. But the lack of a char type, similar to what is in C, gives me a bit of time as a beginner!

+5
source share
2 answers

Dart has no 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)); c++; } 

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

There is also:

 int char_a = 'a'.codeUnitAt(0); print(new String.fromCharCodes(new Iterable.generate(26, (x) => char_a + x))); 
+8
source

Since I was finishing my post and paraphrasing the headline of my questions, I no longer bark the wrong tree thanks to this question about stdout .

It seems that one correct way to write characters is to use stdout.writeCharCode from the dart:io library.

 import 'dart:io'; void ft_print_alphabet() { var c = "a".codeUnits.first; while (c <= "z".codeUnits.first) stdout.writeCharCode(c++); } void main() { ft_print_alphabet(); } 

I still don't know how to manipulate character types, but at least I can print them.

0
source

All Articles