Lisp - String Concatenation



Lisp provides multiple options to do string concatenation.

  • Using concatenate function− concatenate function takes two strings and returns the merged strings.

  • Using format function− format function can merge string with other data types as well apart from string.

  • Using with-output-to-string macro− with-output-to-string macro allows merging string by writing to string stream.

Using concatenate function

The concatenate function concatenates two strings. This is generic sequence function and you must provide the result type as the first argument.

It takes 'string as sequence type specifier followed by the strings to be concetenate.

For example, update the source code file named main.lisp and type the following code in it.

main.lisp

; concatenate and print statement
(write-line (concatenate 'string "Hello, " "World!"))

Output

When you execute the code, it returns the following result −

Hello, World!

Using format function

Format function is a powerful function to create formatted strings.

String can be concatenated with other data types.

For example, update the source code file named main.lisp and type the following code in it.

main.lisp

; concatenate string with number and print statement
(write-line (format nil "Roll No ~a." 51))

Output

When you execute the code, it returns the following result −

Roll No 51.

Using with-output-to-string macro

with-output-to-string writes to string stream.

Conditional merging is easier with with-output-to-string macro.

String can be concatenated with other data types.

For example, update the source code file named main.lisp and type the following code in it.

main.lisp

; concatenate string with number and print statement
(write-line (with-output-to-string (s)
  (write-string "Hello" s)
  (write-string ", " s)
  (write-string "world!" s)) )

Output

When you execute the code, it returns the following result −

Hello, world!
Advertisements