Comment #0 by bearophile_hugs — 2011-07-22T03:16:03Z
Multi-line strings are handy, but I have a small problem with them. This is an example, it has a problem, there is an unwanted newline at the beginning (the situation is the same if you use ` instead of "):
string table = "
- First item: 150
- Second item: 200
- Third item: 105";
(If you are just writing such string then you can use just write() followed by a flush.)
To avoid it you can write this, but both break the alignment in the source code, and they are not nice looking:
string table = "- First item: 150
- Second item: 200
- Third item: 105";
string table =
"- First item: 150
- Second item: 200
- Third item: 105";
This solution adds one ending newline instead:
writeln(q"EOS
- First item: 150
- Second item: 200
- Third item: 105
EOS");
To solve that problem in Python you use this (in Python """ or ''' denote a multi-line string):
table = """\
- First item: 150
- Second item: 200
- Third item: 105"""
The extra slash at the beginning avoids the start newline.
I think it's worth adding this little Python syntax detail to D too.
-------------
Note: this syntax is not meant to solve the more general problem in presence of indentation. In this case you probably need a library solution to de-indent, etc:
void foo()
{
if(blah)
{
writeln("- First item: 150
- Second item: 200
-- Subitem 1
-- Subitem 2
- Third item: 105");
}
}
(Thanks to Nick Sabalausky and Andrej Mitrovic for the suggestions.)
Comment #1 by bearophile_hugs — 2011-07-23T09:12:53Z
Code by Andrej Mitrovic:
http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D&article_id=141106
It shows better why this very small change in D language is not handy to do with a library solution:
import std.algorithm;
import std.stdio;
import std.string;
string stripNewlines(string text)
{
auto x = text.countUntil("\n");
auto y = text.lastIndexOf("\n");
return text[x+1..y];
}
template EOS(string text)
{
enum EOS = stripNewlines(text);
}
void main()
{
writeln(EOS!"
- First item: 150
- Second item: 200
- Third item: 105
");
}
Comment #2 by robert.schadek — 2024-12-13T17:55:55Z