我有一些lisp数字符串字符串要解析为数字:
" 3.000000000E + 00"
" 0.0d0"
" 3"
答案 0 :(得分:3)
请使用Quicklisp提供的parse-number
库。
答案 1 :(得分:2)
(define-condition argument-not-numeric-string (error)
((text :initarg :text :reader text)))
(defun string-to-number (str &optional (radix 10))
(let* ((*read-base* radix)
(value (and (stringp str)
(ignore-errors
(with-input-from-string (in str)
(read in))))))
(if (numberp value)
value
(flet ((read-new-value () (format t "Enter new value: ") (multiple-value-list (eval (read)))))
(restart-case (error 'argument-not-numeric-string :text "Argument needs to be a string with an numeric value")
(use-value (value) :interactive read-new-value (progn (assert (numberp value) (value) "value isn't numeric") value))
(restart-with-string (string) :interactive read-new-value (string-to-number string radix)))))))
以下是测试:
(string-to-number "3.000000000E+00") ; ==> 3.0
(string-to-number "0.0d0") ; ==> 0.0d0
(string-to-number "3") ; ==> 3
(handler-bind ((argument-not-numeric-string #'(lambda (c) (invoke-restart 'restart-with-string "0"))))
(string-to-number "hello")) ; ==> 0
(handler-bind ((argument-not-numeric-string #'(lambda (c) (use-value 0))))
(string-to-number "hello")) ; ==> 0
(string-to-number "aa" 16) ; ==> 170
(string-to-number "gf" 16)
*** - Condition of type ARGUMENT-NOT-NUMERIC-STRING.
The following restarts are available:
USE-VALUE :R1 USE-VALUE
RESTART-WITH-STRING :R2 RESTART-WITH-STRING
ABORT :R3 Abort main loop
Break 1 [50]> :r2
Enter new value: "ff"
; ==> 255
答案 2 :(得分:1)
google之后,请参阅post:
* (with-input-from-string (in "3.000000000E+00")
(read in))
3.0
*