Small problem with multi-line strings

Nick Sabalausky a at a.a
Thu Jul 21 16:27:50 PDT 2011


"bearophile" <bearophileHUGS at lycos.com> wrote in message 
news:j0ac3m$29hj$1 at digitalmars.com...
> Multi-line strings are handy, but I have a small problem.
>
> This is an example, it has a problem, there is an unwanted newline at the 
> beginning:
>
> writeln("
> - First item:  150
> - Second item: 200
> - Third item:  105");
>
>
> To avoid it you can write this, but both break the alignment in the source 
> code, and it's not nice looking:
>
> writeln("- First item:  150
> - Second item: 200
> - Third item:  105");
>
>
> writeln(
> "- First item:  150
> - Second item: 200
> - Third item:  105");
>
>
> To solve this problem in Python you are allowed to write (in Python you 
> need tree " or tree ' to denote a multi-line string):
>
> print """\
> - First item:  150
> - Second item: 200
> - Third item:  105"""
>
>
> The extra slash at the beginning avoids the start newline.
>
> Is this currently possible in D too? If this isn't possible, is it worth a 
> very little enhancement request for the support of that syntax?
>

It's even worse with indentation:

void foo()
{
    if(blah)
    {
        writeln("- First item:  150
            - Second item: 200
                -- Subitem 1
                -- Subitem 2
            - Third item:  105");
    }
}

That's why I created a (CTFEable) fucntion normalize() (maybe could use a 
better name?):

http://www.dsource.org/projects/semitwist/browser/trunk/src/semitwist/util/text.d#L630

void foo()
{
    if(blah)
    {
        // Works properly:
        writeln("- First item:  150
            - Second item: 200
                -- Subitem 1
                -- Subitem 2
            - Third item:  105".normalize());
    }
}

Another example:

Do this:
--------------------
void foo()
{
    enum codeStr = q{
        // Written in the D Programming Langauge
        // by John Doe

        int main()
        {
            return 0;
        }
    }.normalize();
}
--------------------

Instead of this:
--------------------
void foo()
{
enum codeStr =
q{// Written in the D Programming Langauge
// by John Doe

int main()
{
    return 0;
}};
}
--------------------

The resulting string is exactly the same.

I'd be happy to work it into something appropriate for Phobos if people are 
intersted.






More information about the Digitalmars-d-learn mailing list