阅读(2465)
赞(16)
D编程 字符(Character)
2021-09-01 09:46:11 更新
字符由char类型表示,只能容纳256个不同的值。
类型 | 存储空间 | 用途 |
---|---|---|
char | 1个字节 | UTF-8代码单元 |
wchar | 2个字节 | UTF-16代码单元 |
dchar | 4个字节 | UTF-32代码单元和Unicode代码点 |
下面列出了一些有用的字符函数-
- isLower - 确定是否使用小写字符
- isUpper - 确定是否大写字符
- isAlpha - 确定是Unicode字母数字字符(通常是字母还是数字)
- isWhite - 确定是否有空格字符
- toLower - 产生给定字符的小写字母
- toUpper - 产生给定字符的大写字母
import std.stdio;
import std.uni;
void main() {
writeln("Is ğ lowercase? ", isLower('ğ'));
writeln("Is Ş lowercase? ", isLower('Ş'));
writeln("Is İ uppercase? ", isUpper('İ'));
writeln("Is ç uppercase? ", isUpper('ç'));
writeln("Is z alphanumeric? ", isAlpha('z'));
writeln("Is new-line whitespace? ", isWhite('n'));
writeln("Is underline whitespace? ", isWhite('_'));
writeln("The lowercase of Ğ: ", toLower('Ğ'));
writeln("The lowercase of İ: ", toLower('İ'));
writeln("The uppercase of ş: ", toUpper('ş'));
writeln("The uppercase of ı: ", toUpper('ı'));
}
编译并执行上述代码后,将产生以下输出-
Is ğ lowercase? true
Is Ş lowercase? false
Is İ uppercase? true
Is ç uppercase? false
Is z alphanumeric? true
Is new-line whitespace? true
Is underline whitespace? false
The lowercase of Ğ: ğ
The lowercase of İ: i
The uppercase of ş: Ş
The uppercase of ı: I
读取字符
我们可以使用 readf 读取字符,如下所示。
readf(" %s", &letter);
由于D编程支持unicode,因此为了读取unicode字符,我们需要读取两次并写入两次才能获得预期的输出。该如下所示。
import std.stdio;
void main() {
char firstCode;
char secondCode;
write("Please enter a letter: ");
readf(" %s", &firstCode);
readf(" %s", &secondCode);
writeln("The letter that has been read: ", firstCode, secondCode);
}
编译并执行上述代码后,将产生以下输出-
Please enter a letter: ğ
The letter that has been read: ğ
← D编程 函数