Search code examples
d

How to print the string's representation of an object in D?


I'd like to do something equivalent to Python's 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 that in D? Is there a format directive similar to Python's %r?

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


Solution

  • In D strings are not objects and when you use escape characters you are actually storing the character and not the escape itself (which I would expect Python was doing too). So if you want to convert a string into its escaped form you would need to modify the output yourself (I don't know of any library function for this).

    Otherwise Objects can override the toString() function which should produce a string representation of the object.

    Update: Here is an example of repr in D. But note, since the original text is not stored anywhere in the executable it will convert literal representations too. There shouldn't be an issue with Unicode as the normal integrity of string is intact.

    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);
    }