View source code
Display the source code in std/string.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Function std.string.toStringz

immutable(char)* toStringz (
  scope const(char)[] s
) pure nothrow @trusted;

Parameters

NameDescription
s A D-style string.

Returns

A C-style null-terminated string equivalent to s. s must not contain embedded '\0''s as any C function will treat the first '\0' that it sees as the end of the string. If s.empty is true, then a string containing only '\0' is returned.

Important Note: When passing a char* to a C function, and the C function keeps it around for any reason, make sure that you keep a reference to it in your D code. Otherwise, it may become invalid during a garbage collection cycle and cause a nasty bug when the C code tries to use it.

Example

import core.stdc.string : strlen;
import std.conv : to;

auto p = toStringz("foo");
writeln(strlen(p)); // 3
const(char)[] foo = "abbzxyzzy";
p = toStringz(foo[3 .. 5]);
writeln(strlen(p)); // 2

string test = "";
p = toStringz(test);
writeln(*p); // 0

test = "\0";
p = toStringz(test);
writeln(*p); // 0

test = "foo\0";
p = toStringz(test);
assert(p[0] == 'f' && p[1] == 'o' && p[2] == 'o' && p[3] == 0);

const string test2 = "";
p = toStringz(test2);
writeln(*p); // 0

assert(toStringz([]) is toStringz(""));

Authors

Walter Bright, Andrei Alexandrescu, Jonathan M Davis, and David L. 'SpottedTiger' Davis

License

Boost License 1.0.