How to escape control characters?

Salih Dincer salihdb at hotmail.com
Sun Sep 22 12:56:41 UTC 2024


On Thursday, 19 September 2024 at 14:30:08 UTC, Gerardo Cahn 
wrote:
> On Wednesday, 24 August 2022 at 08:12:33 UTC, Salih Dincer 
> wrote:
>> On Tuesday, 23 August 2022 at 23:17:21 UTC, Salih Dincer wrote:
> ...
>> Actually, both structures could be combined:
>>
>> ```d
>> struct EscapedString
>> {
>>    string[1] str;
>>    this(string str) @nogc pure nothrow @safe
>>    {
>>...(rest clipped)
>> ```
>
> Thanks to all.  I am using the code listed here.  I can't but 
> feel like Salieri with Mozart: I know enough D to appreciate 
> this thread, but not enough to create this on my own...

This must be a metaphor, from the past...

I would like to thank you for saying "hello" to the silence. 
Thanks to you, I have just developed the missing parts of the 
code. I am sure that if the silent majority criticized such 
codes, the field would be beautiful.

I hadn't thought about UTF codes before, they seem to work. What 
do you think?


```d
import std.stdio;

void main()
{
   enum str = r"\tHello\xfeD\r\nProgramming\0\nWorld!\b\f";

   auto u = str.unescaped();
   auto e = u.escaped();
   assert(e == str);
   u.unescaped.writeln;
}

auto escaped(string str)
{
   import std.algorithm : map;
   import std.conv : to, toChars;
   import std.string : format;

   return str.map!(chr => ()
   {
     auto code = chr.to!ulong;
     if (code >= 0x7f)
     {
       return code.toChars!(16, char)
                  .format!"\\x%-(%c%)";
     }
     switch (code)
     {
       case '\0': return `\0`;
       case '\b': return `\b`;
       case '\f': return `\f`;
       case '\t': return `\t`;
       case '\n': return `\n`;
       case '\r': return `\r`;
       case '"':  return `\"`;
       case '\'': return `\'`;
       case '\\': return `\\`;
       //case ' ':  return `\s`;
       default: return chr.to!string;
     }
   }()).format!"%-(%s%)";
}

string unescaped(string str)
{
   import std.format : fs = FormatSpec;
   import std.format : uv = unformatValue;
   fs!char f;
   auto s = `["` ~ str ~ `"]`;
   return uv!(string[])(s, f)[0];
}
```
SDB at 79


More information about the Digitalmars-d-learn mailing list