Lisp の文字列操作-Ver20121207
Lisp の文字列操作-Ver20120318 - Shammerismにsubstitute-ifを追加。
数値を文字列に変換する->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) ?
char 同士を比較
? (char= #\a #\a) T ? (char= #\/ #\/) T ? (char= #\Space #\ ) T ? (char= #\x #\X) NIL ? (char-equal #\x #\X) T ?
文字列を byte array に変換
ClozureCL
? (encode-string-to-octets "abcdefg" :external-format :utf-8) #(97 98 99 100 101 102 103) 7 ?
SBCL
実行環境がすぐに用意できないので関数だけ。sb-ext:octets-to-string を使用する。
byte array を文字列に変換
ClozureCL
? (defvar x (make-array 0 :fill-pointer 0 :adjustable t :element-type '(unsigned-byte 8))) X ? (vector-push-extend 97 x) 0 ? (vector-push-extend 98 x) 1 ? (vector-push-extend 99 x) 2 ? (vector-push-extend 100 x) 3 ? (vector-push-extend 101 x) 4 ? (vector-push-extend 102 x) 5 ? (decode-string-from-octets x :external-format :utf-8) "abcdef" 6 ?
SBCL
実行環境がすぐに用意できないので関数だけ。sb-ext:octets-to-string を使用する。
ある条件に合致する文字を変換(substitute-if)
? (substitute-if #\0 #'oddp '(1 2 3 4 5 6)) (#\0 2 #\0 4 #\0 6) ? (substitute-if #\0 #'evenp '(1 2 3 4 5 6)) (1 #\0 3 #\0 5 #\0) ?