在 Common Lisp 中,字符串是字符的向量。字符串写成用双引号括起来的一串字符(例如 "Hello World!")。
只有当给定的值是字符串时,stringp谓词才会返回 true。
可以用subseq函数把字符串拆分成子字符串,它接收一个字符串、一个起始下标,以及一个可选的结束下标。下标从 0 开始。
(subseq "Hello World" 1 5) ; => "ello"
(subseq "skip to the end" 5) ; => "to the end"
可以用string=比较字符串是否相等。如果要忽略字符的大小写,可以用string-equal。
(string= "macaroni" "macaroni") ; => T
(string= "macaroni" "MACARONI") ; => NIL
(string-equal "macaroni" "MACARONI") ; => T
字符串的大小写转换,比如转成大写、转成小写和首字母大写,可以分别用string-upcase、string-downcase和string-capitalize完成。
(string-upcase "not too loud") ; => "NOT TOO LOUD"
(string-downcase "YELL IT FROM THE ROOFTOPS") ; => "yell it from the rooftops"
(string-capitalize "practical COMMON LiSP") ; => "Practical Common Lisp"
在本练习中,你将编写一些代码,帮助 Lisp 外星人 Larry 解析和格式化日志字符串。这些日志字符串来自各种系统,需要经过处理,才能把其中的消息显示在一个信息丰富的监控界面上。
日志字符串的形式为"[<level>]: <message>"。级别会是以下值之一:info、warn 或 ohno。
定义一个函数log-message,它接受一个日志字符串,并求值得到其中包含的消息。
(log-message "[ohno]: whoops!") ; => "whoops!"
日志字符串的级别决定了它的严重程度。
info时,严重程度为:everything-ok
warn时,严重程度为:getting-worried
ohno时,严重程度为:run-for-cover
定义一个函数log-severity,它接受一个日志字符串,并求值得到对应的严重程度。
(log-severity "[warn]: might want to get that checked") ; => :getting-worried
遗憾的是,有时日志字符串的格式并不总是正确。具体来说,日志级别可能并非如上文所述那样全部为小写。请修改log-severity来处理这种情况。
(log-severity "[WaRn]: string case system failing") ; => :getting-worried
根据严重程度的不同,消息需要以不同的方式修改:
:everything-ok时,消息应改为全部小写。:getting-worried时,消息应改为每个单词首字母大写。:run-for-cover时,消息应改为全部大写。定义一个函数log-format,它接受一条日志消息,并求值得到格式正确的消息。
(log-format "[ohno]: whoops!") ; => WHOOPS!