Lisp の文字列操作
数値を文字列に変換する write-to-string など、いくつか記事にしたこともあるが、整理したことがないっぽいので整理してみる。
数値を文字列に変換する->write-to-string
? (setf a 1) 1 ? (type-of a) BIT ? (setf string-1 "aaa") "aaa" ? (concatenate 'string string-1 a) > Error: The value 1 is not of the expected type SEQUENCE. > While executing: CCL::SEQUENCE-TYPE, in process listener(1). > Type :POP to abort, :R for a list of available restarts. > Type :? for other options. 1 > q ? (concatenate 'string string-1 (write-to-string a)) "aaa1" ?
文字(char)を文字列型(string)にする->string
? (setf a '#\a) #\a ? (type-of a) STANDARD-CHAR ? (setf x "x") "x" ? (type-of x) (SIMPLE-BASE-STRING 1) ? (concatenate 'string x a) > Error: The value #\a is not of the expected type SEQUENCE. > While executing: CCL::SEQUENCE-TYPE, in process listener(1). > Type :POP to abort, :R for a list of available restarts. > Type :? for other options. 1 > q ? (concatenate 'string x (string a)) "xa" ?
文字列型(string)を文字(char)にする->coerce
? (setf a '#\a) #\a ? (setf x "x") "x" ? (setf vec (make-array 0 :element-type 'character :fill-pointer 0 :adjustable t)) "" ? (vector-push-extend a vec) 0 ? vec "a" ? (vector-push-extend x vec) > Error: "x" doesn't match array element type of "a". > While executing: VECTOR-PUSH-EXTEND, in process listener(1). > Type :POP to abort, :R for a list of available restarts. > Type :? for other options. 1 > q ? (vector-push-extend (coerce x 'character) vec) 1 ? vec "ax" ?
文字列をcharのListに変換->coerce
? (setf x "abcedfg") "abcedfg" ? (coerce x 'list) (#\a #\b #\c #\e #\d #\f #\g) ?
これらの詳細は、The Common Lisp Cookbook - Stringsにある。他にも追加したくなるものが今後出てくるかもしれないが、とりあえずは以上。