将 int 值赋给 char

Assign int value to char

在学习 C++ 和 D 时,我试图通过测试两种语言的一些代码来比较易用性。

所以,在 C++ 中我有这样的东西(没有显示完整的 C++ 代码,它只是为了演示):

char src[] = "some10char";
char des[];

for (int i=0; i<1000; i++)
{
    src[9] = '0' + i % (126 - '0');
    des = src;
}

在上面的'pseudo'中,for循环体中的第一行不仅分配了int值,而且还试图避免不可打印的值。

我怎么能在 D 中做同样的事情?

到目前为止,我已经成功地将 int 转换为 char,但我不知道我是否正确:

char[] src = "some10char".dup;
char[] dst;

for (int i=0; i<1000; i++)
{   
    if (i<15) 
        src[src.length-1] = cast(char)(i+15);
    else
        src[src.length-1] = cast(char)(i);

    dst = src.dup // testing also dst = src;
}

您可以在 D 中添加和减去字符文字,就像在您的 C++ 示例中一样,例如:

import std.stdio;

char[] str;

void main(string[] args)
{
    for(int i=0; i<1000; i++)
    {
        str ~= cast(char)( i % (0x7F - '0') + '0') ;
    }
    writeln(str);
}

仅打印超过 0 且小于 0x7F 的 ascii 字符。该字符隐式转换为 int,然后 i 上的最终操作(它本身给出 int)然后显式转换为 char(因此 modulo/mask 为 0xFF) .

更多地道的D代码:

char[] source = "some10char".dup; // or cast(char[])"some10char";
char[] destination; // = new char[source.length];

foreach (i; 0 .. 1000)
{
    source[$ - 1] = cast(char)('0' + i % (126 - '0'));

    destination = source.dup; // dup will allocate every time
    //destination[] = source[]; // copying, but destination must have same length as source
}