<div dir="ltr">does that work?<div><div>string escapeD(string a){</div><div><span class="" style="white-space:pre"> </span>import std.array:replace;</div><div><span class="" style="white-space:pre"> </span>return `r"`~a.replace(`"`,`" "\"" r"`)~`"`;</div>
<div>}<br></div></div></div><div class="gmail_extra"><br><br><div class="gmail_quote">On Sun, Apr 20, 2014 at 11:14 AM, monarch_dodra via Digitalmars-d-learn <span dir="ltr"><<a href="mailto:digitalmars-d-learn@puremagic.com" target="_blank">digitalmars-d-learn@puremagic.com</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div class="">On Sunday, 20 April 2014 at 17:55:25 UTC, Ellery Newcomer wrote:<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
is there a function in phobos anywhere that takes a string and escapes it into a string literal suitable for string mixins? something like<br>
<br>
assert (f("abc\ndef") == "\"abc\\ndef\"");<br>
</blockquote>
<br></div>
It's a bit hackish, but it avoids deploying code and reinventing anything. You can use format "string-range" formating to print the string escaped. Catch that, and then do it again:<br>
<br>
string s = "abc\ndef";<br>
writefln("[%s]\n", s); //raw<br>
<br>
s = format("%(%s%)", [s]);<br>
writefln("[%s]\n", s); //escaped<br>
<br>
s = format("%(%s%)", [s]);<br>
writefln("[%s]\n", s); //escapes are escaped<br>
<br>
As you can see from the output, after two iterations:<br>
<br>
[abc<br>
def]<br>
<br>
["abc\ndef"]<br>
<br>
["\"abc\\ndef\""]<br>
<br>
I seem to recall that printing strings "escaped" has been requested before, but, AFAIK, this is the best we are currently providing.<br>
<br>
Unless you call std.format's "formatElement" directly. However, this is an internal and undocumented function, and the fact it isn't private is probably an oversight.<br>
</blockquote></div><br></div>