2

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;
}
4

1 に答える 1

3

writeln の最も簡単な方法は、カンマで区切ることです。

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

各引数は自動的に文字列に変換されて出力されます。writeln は、任意の数の引数を取ることができます。

ただし、一般に、D での文字列の連結は次の~演算子で行われstring a = b ~ cます。b と c はどちらも文字列型でなければなりません。

文字列に変換するには、次のようにします。

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 は、to!int("12") == 12 など、他の型との間で変換することもできます。

したがって、そこでstring s = to!string(a) ~ " cool " ~ to!string(c);動作します。

于 2012-12-19T00:54:20.537 に答える