'how to write string literal with new lines in Pharo

How do you write a string literal with new line characters in Pharo 9? I tried the following but neither of them inserted the new line:

a := 'paragraph1\n\nparagraph2'.
a := 'paragraph1\\n\\nparagraph2'.

The only way I could see to do it was through concatenation like so:

a := 'paragraph' , 
     (String with: Character cr with: Character cr),
     'new paragraph' , 
     (String with: Character cr with: Character cr)

Is there a simpler (and shorter) way to do this?



Solution 1:[1]

You just do your line:

multiLineString := 'paragraph1
paragraph2
paragraph3'.

Pharo (as any other Smalltalk AFAIK) has multiline strings, you do not need any special notation as in Python or others.

EDIT: Note that while my example will be a literal, yours will not (there will be 2 literals there, and the resulting string will not be a literal.
EDIT 2: There is also String cr.
EDIT 3: It can also be constructed with streams:

myMultiLineString := String streamContents: [ :stream |
    stream 
        nextPutAll: 'paragraph1'; cr;
        nextPutAll: 'paragraph2'; cr ]

Solution 2:[2]

You can use the <n> placeholder in your String and send it the expandMacros message - this will expand the placeholder to the platform line separator(s):

a := 'paragraph1<n>paragraph2' expandMacros.

expandMacros and its variants also accept placeholders for tabs, cr, lf and parameters. See the comment to String>>expandMacrosWithArguments: for more details.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 John Aspinall