www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - compute from a string the text of a string literal

reply Carl Sturtivant <sturtivant gmail.com> writes:
Hello,
I'd like a function like this,
```
string image(string s)
```
that maps any string s into the doubly quoted backslash escaped 
text that would be a string literal for s were it pasted into a 
program. Perhaps with a second parameter with detailed options.

Is there something out there I could use?
Jan 17
parent reply Paul Backus <snarwin gmail.com> writes:
On Wednesday, 17 January 2024 at 18:44:14 UTC, Carl Sturtivant 
wrote:
 Hello,
 I'd like a function like this,
 ```
 string image(string s)
 ```
 that maps any string s into the doubly quoted backslash escaped 
 text that would be a string literal for s were it pasted into a 
 program. Perhaps with a second parameter with detailed options.

 Is there something out there I could use?
There's a function that does this in Phobos, but it's `private`. Currently, the only way to access it is by calling `to!string` or `format` on a range that contains the string you want to convert as an element: ```d void main() { import std.range, std.conv, std.stdio; string s = `"foo"\bar`; string escaped = only(s).to!string[1 .. $-1]; // slice off [ and ] writeln(escaped); // "\"foo\"\\bar" } ```
Jan 17
parent Carl Sturtivant <sturtivant gmail.com> writes:
On Wednesday, 17 January 2024 at 18:53:48 UTC, Paul Backus wrote:
 There's a function that does this in Phobos, but it's 
 `private`. Currently, the only way to access it is by calling 
 `to!string` or `format` on a range that contains the string you 
 want to convert as an element:

 ```d
 void main()
 {
     import std.range, std.conv, std.stdio;

     string s = `"foo"\bar`;
     string escaped = only(s).to!string[1 .. $-1]; // slice off 
 [ and ]
     writeln(escaped); // "\"foo\"\\bar"
 }
 ```
Great! I'll use that!
Jan 17