char[] to string

Timon Gehr timon.gehr at gmx.ch
Sat Jun 11 15:35:20 PDT 2011


On 2011-06-10 19:56, Jonathan Sternberg wrote:
> Why doesn't this work?
>
> import std.stdio;
>
> string copy_string(char [] input)
> {
>     return input.dup;
> }
>
> int main()
> {
>     char [] buf = ['h', 'e', 'l', 'l', 'o'];
>     writeln( copy_string(buf) );
> }
>
> I want to do something more complex. In my code, I want to have a dynamic
> array that I can append stuff into and then return it as a string. In C++,
> a non-const variable can be implicitly converted into a const. I know
> string is an alias for const char. Is there a reason why it won't
> implicitly convert it?
>
> I hesitate to use cast for this type of thing as it probably indicates I'm
> doing something fundamentally wrong as I'm just starting to learn the
> language.

Hi,

You can append to a string. You only need char[] if you have to modify individual
characters.

// idup fixes your specific problem
string copy_string(char [] input)
{
    return input.idup;
}

string build_string(string str1, string str2){
    string result;
    result~=str1;
    foreach(i;0..3) result~=str2;
    return result;
}

unittest{ assert(build_string("hi","lo") == "hilololo"); }

If you really need char[] and you know that there is only one mutable reference to
your data, then you can use std.exception.assumeUnique. (No idea why it is *there*
though)

import std.exception;

string toUpper(char[] str){
    char[] result = str.dup;
    foreach(ref x;result) if('a'<=x && x<='z') x+='A'-'a';
    return result.assumeUnique(); // this is only safe if there really is only one
reference to your data
}


Timon


More information about the Digitalmars-d-learn mailing list