Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

Practical Lisp

Name: Anonymous 2011-03-03 8:09

How to split and join a line by the delimiter in Common Lisp?

In Python it's:
>>> 'hax,my,anus'.split(',')
['hax', 'my', 'anus']


and

>>> ','.join(['hax', 'my', 'anus'])
'hax,my,anus'


respectively.

Name: Anonymous 2011-03-03 8:14

>>1
My instincts tells me that you should use  format for this.

Name: Anonymous 2011-03-03 8:30

>>1
> (string-join '("hax" "my" "anus") ".")
"hax.my.anus"

> (regexp-split "," "hax,my,anus")
'("hax" "my" "anus")


Don't know in CL. You can use format for joining. Or http://www.cliki.net/SPLIT-SEQUENCE

Name: Anonymous 2011-03-03 9:03

>>3
Some library had a join, but I can't remember its name. It's also possible to do with FORMAT. You're also right about SPLIT-SEQUENCE, although you can use CL-PPCRE to split by regular expression.

My implementation of string-join (works the same as your example):

(defun mappend (fn list
                &rest otherlists
                &aux (list (copy-list list)) (otherlists (copy-list otherlists)))         
  (apply #'mapcan fn list otherlists))

(defun insert-inbetween (list element &key (no-last t))
  (let ((new-list
         (mappend #'(lambda (e) (list e element)) list)))
    (if no-last (butlast new-list) new-list)))

(defun string-join (strings delim)
  (apply #'concatenate 'string (insert-inbetween strings delim)))

CL-USER> (string-join '("what" "is" "this" "about") ".")
"what.is.this.about"


Using FORMAT:

(defun string-join (strings delim)
  (format nil (format nil "~~{~~a~~^~a~~}" delim) strings))


With split-sequence:

CL-USER> (split-sequence #\  "What is this?")
("What" "is" "this?")
13


With CL-PPCRE:

CL-USER> (split ", " "What, Is, This.")
("What" "Is" "This.")

Don't change these.
Name: Email:
Entire Thread Thread List