Gaucheで文字列操作できるの?

というわけでいろいろ試してみた.

まずはじめに文字の扱い.

文字は#\のあとにその文字を書く.h,e,l,l,oからなるリストは,

'(#\h #\e #\l #\l #\o)

でできる.

で,文字列.

文字列はほかのプログラミング言語と一緒で””で囲めばよい.helloという文字列は

"hello"

で表せる.

複雑な処理をしようと思うと,基本的にはsrfi-13という文字列ライブラリがあるので,それを使えばよい.

というわけで,最初に

(use srfi-13)

これでライブラリの読み込みができた.

で,

(string->list "hello")

とすると,文字列⇒リストの変換.

(list->string '(#\h #\e #\l #\l #\o)) ; "hello"

とすると,リスト⇒文字列の変換.直観的.

大文字,小文字の置き替えは,

(character-upcase #\a)     ; A
(string-upcase "hello")    ; HELLO
(character-downcase #\A)   ; a
(string-downcase "HELLO")  ; hello

でOK.

頭文字だけ大文字にする時は

(string-titlecase "hello world")   ;Hello World

でOK.

部分文字列の取り出しは

(substring "Hello World!" 6 11)    ;World

で,6文字目から11文字目の前まで取り出せる.

連結,分割も簡単

(string-append "hello" "world")       ; "hello world"
(string-join ("hello" "world") ", ")  ; "hello, world"
(string-join ("hello" "world") "||")  ; "hello||world"
(string-split "hello world" " ")      ; ("hello" "world")

正規表現は,#/正規表現/で表せる.

その正規表現にマッチするかどうかのテストは

(rxmatch #/test/ "hellotestworld")

マッチした結果を使って何かをしたいときは上のrxmatchを使って

(rxmatch-if (rxmatch #/test/ "hellotestworld") (str) str "not match")

これは,マッチすればマッチした部分を(str)に入れて,strを,そうでなければ”not match”を返す.要は if-then-elseな文.

マッチした文字列を置き換えたいときは

(string-replace #/test/ "hellotestworld" " TEST ") ; hello TEST world"

でOK.

文字列まわりの関数で使いそうなやつを一通りおぼえた.

コメントする