Lisp - Merging Strings



Lisp provides multiple ways to merge strings. We'll explore multiple ways to merge strings.

  • concatenate method to join two strings.

  • format method to join multiple strings.

  • merge method to join sequence of strings.

Example - Using concatenate() function to merge strings

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 merged.

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

main.lisp

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

Output

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

Hello, World!

Example - Using format() function to merge strings

Format function is a powerful function to create formatted strings. String can be merged easily using format() method.

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

main.lisp

; concatenate string and print statement
(write-line (format nil "Hello ~a." "World"))

Output

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

Hello World.

Example - Using merge() function to merge strings

The merge function takes two sequences of strings and a predicate and returns a sequence produced by merging the two sequences, according to the predicate.

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

main.lisp

; join sequence of vector of strings using merge() function
(write (merge 'vector (vector "Rishi" "Zara" "Priyanka") 
   (vector "Anju" "Anuj" "Avni") #'string<))

; join sequence of strings using merge() function
(write (merge 'vector '("Rishi" "Zara" "Priyanka") 
   '("Anju" "Anuj" "Avni") #'stringlt;))

Output

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

#("Anju" "Anuj" "Avni" "Rishi" "Zara" "Priyanka")
Advertisements