如何在Dart中使用char类型? (打印字母表) [英] How to work with char types in Dart? (Print alphabet)
问题描述
我想学习 Dart语言
我们C池中的第一个练习是写一个函数 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);
}
然而,据我所知,Dart的当前版本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中那样的 char
类型给我一个很难的时间,作为一个初学者!
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没有字符类型。
Dart does not have character types.
要将代码点转换为字符串, c $ c> String 构造函数 String.fromCharCode
:
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++;
}
对于这样的简单东西,我会使用print
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)));
这篇关于如何在Dart中使用char类型? (打印字母表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!