如何在达特char型工作? (打印字母) [英] How to work with char types in Dart? (Print alphabet)

查看:161
本文介绍了如何在达特char型工作? (打印字母)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想学习飞镖语言,通过转由我校C编程给出的exercices。

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

在我们的C池中的第一个exercice是的编写一个函数 print_alphabet(),打印字母小写的;它是被禁止直接打印的字母

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.

在POSIX C,直截了当的解决办法是:

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

不过,据我所知,飞镖(1.1.1)的当前版本没有处理字符的简单方法。我想出了(我的第一个版本),最远的是这样的:

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

它打印每一个字符,每行一个的ASCII值,作为一个字符串(97......122)。不是真的是我的本意......

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

我试图寻找这样做的正确方法。但缺少了字符键入像在C的给我一点很难,作为一个初学者!

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!

推荐答案

飞镖不具有的性格类型。

Dart does not have character types.

要一个code点转换为字符串,使用String构造String.fromChar code:

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.

还有:

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

这篇关于如何在达特char型工作? (打印字母)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆