In visual lisp, you can use (atoi "123")
to convert "123"
to 123
. It seems there is no "atoi" like function in clisp ?
any suggestion is appreciated !
Now i want to convert '(1 2 3 20 30)
to "1 2 3 20 30"
, then what's the best way to do it ?
parse-interger
can convert string to integer, and how to convert integer to string ? Do i need to use format
function ?
(map 'list #'(lambda (x) (format nil "~D" x)) '(1 2 3)) => ("1" "2" "3")
But i donot know how to cnovert it to "1 2 3"
as haskell does:
concat $ intersperse " " ["1","2","3","4","5"] => "1 2 3 4 5"
Sincerely!
In Common Lisp, you can use the read-from-string
function for this purpose:
> (read-from-string "123")
123 ;
3
As you can see, the primary return value is the object read, which in this case happens to be an integer. The second value—the position—is harder to explain, but here it indicates the next would-be character in the string that would need to be read next on a subsequent call to a reading function consuming the same input.
Note that read-from-string
is obviously not tailored just for reading integers. For that, you can turn to the parse-integer
function. Its interface is similar to read-from-string
:
> (parse-integer "123")
123 ;
3
Given that you were asking for an analogue to atoi
, the parse-integer
function is the more appropriate choice.
Addressing the second part of your question, post-editing, you can interleave (or "intersperse") a string with the format
function. This example hard-codes a single space character as the separating string, using the format
iteration control directives ~{
(start), ~}
(end), and ~^
(terminate if remaining input is empty):
> (format nil "Interleaved: ~{~S~^ ~}." '(1 2 3))
"Interleaved: 1 2 3."
Loosely translated, the format string says,
For each item in the input list (
~{
), print the item by its normal conversion (~S
). If no items remain, stop the iteration (~^
). Otherwise, print a space, and then repeat the process with the next item (~}
).
If you want to avoid hard-coding the single space there, and accept the separator string as a separately-supplied value, there are a few ways to do that. It's not clear whether you require that much flexibility here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With