How to work with char types in Dart? (Print alphab

2019-04-28 05:00发布

问题:

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 print_alphabet() 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);
        c++;
    }
}

int     main(void)
{
    print_alphabet();
    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)
  {
    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 really what I intended…

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

回答1:

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));
  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)));


回答2:

As I was finalizing my post and rephrasing my question’s title, I am no longer barking up the wrong tree thanks to this question about stdout.

It seems that one proper way of writing 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 have no clue about how to manipulate character types, but at least I can print them.



标签: c dart