Search code examples
concatenationd

Concatenation in writeln?


I am new to D and I am just trying things out. A book I am using gave me an example of a generic Binary Search method. I then wanted to make my own main method to print out the results just for fun. I come from Java where String Concatenation is simply done using the + operator.

But when I try that in D, it says that the two types (String and bool in this case) are incompatible. I tried to use the << operation instead as I've seen in C++ but then it told me that it wasn't an integral. How do I concatenate then?

import std.stdio, std.array;

void main() {
    bool b = binarySearch([1, 3, 6, 7, 9, 15], 6);
    writeln("6 is in array: " + b);
    b = binarySearch([1, 3, 6, 7, 9, 15], 5);
    writeln("5 i sin the array: "  + b);

}

bool binarySearch(T)(T[] input, T value) {
    while(!input.empty) {
        auto i = input.length / 2;
        auto mid = input[i];
        if(mid > value) input = input[0 .. i];
        else if (mid < value) input = input[i + 1 .. $];
        else return true;
    }
    return false;
}

Solution

  • Easiest for writeln is to just separate it with commas.

    writeln("6 is in array: ", b);
    

    Each argument is automatically converted to string and outputted. writeln can take any number of arguments.

    In general though, string concat in D is done with the ~ operator: string a = b ~ c; Both b and c have to be of type string.

    To convert to string, you can do:

    import std.conv;
    int a = 10;
    string s = to!string(a); // s == "10"
    bool c = false;
    string s2 = to!string(c); // s2 == "false"
    

    std.conv.to can also convert to and from other types, e.g. to!int("12") == 12.

    Thus, string s = to!string(a) ~ " cool " ~ to!string(c); will work there.