Frage

So I was trying to make an asterisk pyramid using D. First of all I noticed that concatenation seems to be impossible. Writing out something like writeln("foo" + "bar") will give you a syntax error. So instead I tried multiplying the strings like in python, that didn't work with double quoted strings, but with single quoted strings something weird happens.

If you type in this

import std.stdio;
void main()
{
    foreach (i; 0 .. 10)
    {
        writeln(i*'0');
    }
}

it will return a bunch of integers. Could anyone explain why this happens? And letting me know how to concatenate strings will also be really helpful.

thanks!

War es hilfreich?

Lösung

The '0' is not a string, it is a character, which uses ASCII encoding. The number is being multiplied with the encoding's integer id. For example, the encoding for ASCII's 'A' is 65.

import std.stdio;
int main()
{
        writeln( cast(int)'A' );
        writeln( 10 * 'A' );
        return 0;
}

This program will print 65 and 650 because the character is being converted to an integer in both cases.

To solve the original concatenation problem you can use the '~' operator for concatenating two arrays, or use "array1 ~= array2" to append array2 onto array1 in one statement.

Andere Tipps

First solution that comes to mind:

char[5] arr3 = 's';
writeln(arr3);

Two alternatives are std.array.replicate and std.range.repeat:

import std.array;
import std.stdio;

void main() {
    auto arr = replicate(['s'], 5); // lazy version: http://dlang.org/phobos/std_range.html#repeat
    // or
    auto arr2 = ['s'].replicate(5);
    writeln(arr);
    writeln(arr2);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top