>> print ...">

How to print a string representation of an object in D?

I would like to do something equivalent to Python repr:

>>> x = "a\nb\nc"

>>> print x
a
b
c
>>> repr(x)
"'a\\nb\\nc'"

>>> print repr(x)
'a\nb\nc'

How can I do this in D? Is there a format directive similar to Python %r?

EDIT: I want to be able to print strings in their escaped form for debugging purposes (I just started learning D and I am writing dumb text processing functions).

+3
source share
4 answers

D , escape-, , ( , Python ). , , ( - ).

toString(), .

: D. : , . Unicode , .

import std.stdio;
import std.exception;

void main() {
    writeln(repr("This\nis\n\t*My\v Test"));
}

string repr(string s) {
    char[] p;
    for (size_t i; i < s.length; i++)
    {
        switch(s[i]) {
            case '\'':
            case '\"':
            case '\?':
            case '\\':
                p ~= "\\";
                p ~= s[i];
                break;
            case '\a':
                p ~= "\\a";
                break;
            case '\b':
                p ~= "\\b";
                break;
            case '\f':
                p ~= "\\f";
                break;
            case '\n':
                p ~= "\\n";
                break;
            case '\r':
                p ~= "\\r";
                break;
            case '\t':
                p ~= "\\t";
                break;
            case '\v':
                p ~= "\\v";
                break;
            default:
                p ~= s[i];
                break;
        }
    }

    return assumeUnique(p);
}
+2

D WYSIWYG:

r"thestring"
`thestring`

,

import std.stdio;

void main()
{
    auto a = r"hello\nworld";
    auto b = `hello\nworld`;

    writeln(a);
    writeln(b);
}

hello\nworld
hello\nworld

, , , escape-, - , std.string.replace(), . , , :

str.replace("\n", "\\n");

'\ t', '\ r', '\' .. , . WYSIWYG .

+1

, escape- . , (, ), .

If you control the source, you can use raw strings . Just put rin front of your line.

"a\tb" => "a    b"
r"a\tb" => "a\tb"
+1
source

The standard library D does not contain such a function, but it must be written trivially. Just scroll through the line and replace each event "\n"with "\\n", etc.

+1
source

Source: https://habr.com/ru/post/1770028/


All Articles