delphistring-interpolationmultilinestringdelphi-12-athens

How can I use a variable in a multiline string in Delphi?


Delphi 12 introduced multiline strings and I'm trying to figure out how it works, coming from a JavaScript background. There I can directly have variables in multiline strings such as:

const myName = 'Martin';
const myString = `Hi ${myName},
Say hello to 
multi-line
strings!`;

And that would replace ${myName} with the content of the variable. How can this be achieved in Delphi with the new ''' multiline Strings?


Solution

  • Delphi does not support String interpolation, as some languages do, like Java, C#, etc. The new multi-line syntax simply allows a string literal to span across line breaks, nothing more.

    To do what you want, you would still need to use plain string concatenation, e.g.:

    const myName = 'Martin';
    const myString = 'Hi ' + myName +
    '''
    ,
    Say hello to 
    multi-line
    strings!
    ''';
    

    The closest thing that Delphi has to String interpolation is SysUtils.Format(), e.g.:

    const myName = 'Martin';
    const myString = Format(
    '''
    Hi %s,
    Say hello to 
    multi-line
    strings!
    ''',
    [myName]);