char[] to string
Jonathan M Davis
jmdavisProg at gmx.com
Fri Jun 10 21:32:44 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.
string is an alias for immutable(char)[]. The elements of a string can never
be altered. dup returns a mutable copy of a string (not const, not immutable).
idup returns an immutable copy. So, in this case you want idup, not dup. Even
better though, would be to use std.conv.to - e.g. to!string(input). This will
convert input to a string, but it has the advantage that if input is already a
string, then it'll just return the string rather than making another copy like
idup would.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list