Search code examples
smalltalkpharo

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

  • 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 ]