Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiplying a string by an integer returns integers?

Tags:

string

d

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!

like image 592
Skiddzie Avatar asked Apr 22 '14 04:04

Skiddzie


Video Answer


2 Answers

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.

like image 105
h4tch Avatar answered Sep 22 '22 21:09

h4tch


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);
}
like image 30
DejanLekic Avatar answered Sep 23 '22 21:09

DejanLekic