[TOC=2]
## 11.1?簡介
我只介紹了表和數,因為它們在Scheme中最為常用。然而,Scheme也有像**字符(Character)**、**字符串(String)**、**符號(Symbol)**、**向量(Vector)**等的其它數據類型,我將在11到14章節中介紹它們。
## 11.2?字符
在某個字符前添加`#\`來表明該物是一個字符。例如,`#\a`表示字符a。字符`#\Space`、`#\Tab`、`#\Linefeed`和`#\Return`分別代表空格(Space)、制表符(Tab),Linefeed和返回(Return)。R5RS中定義了下面的與字符相關的函數。
`(char? obj)`
如果obj是一個字符則返回`#t`。
`(char=? c1 c3)`
如果c1和c2是同一個字符的話則返回`#t`。
`(char->integer c)`
將c轉化為對應的整數(字符代碼,character code)。示例:`(char->integer #\a) => 97`
`(integer->char n)`
該函數將一個整數轉化為對應的字符。
`(char<? c1 c2)`
`(char<= c1 c2)`
`(char> c1 c2)`
`(char>= c1 c2)`
這些函數用于比較字符。實際上,這些函數比較的是字符代碼的大小。例如,`(char<? c1 c2)`等同于`(< (char->integer c1) (char->integer c2))`
`(char-ci=? c1 c2)`
`(char-ci<? c1 c2)`
`(char-ci<=? c1 c2)`
`(char-ci>? c1 c2)`
`(char-ci>=? c1 c2)`
這些比較函數對大小寫不敏感。
`(char-alphabetic? c)`
`(char-numeric? c)`
`(char-whitespace? c)`
`(char-upper-case? c)`
`(char-lower-case? c)`
這些函數分別用于檢測字符c是否為字母、數字、空白符、大寫字母或小寫字母。
`(char-upcase c)`
`(char-downcase c)`
這些函數分別返回字符C對應的大寫或小寫。
## 11.3?字符串
字符串通過兩個閉合的雙引號表示。例如,”abc”表示字符串abc。R5RS定義了下面的函數。
`(string? s)`
如果`s`是一個字符則返回`#t`。
`(make-string n c)`
返回由`n`個字符`c`組成的字符串。參數`c`可選。
`(string-length s)`
返回字符串`s`的長度。
`(string=? s1 s2)`
如果字符串`s1`和`s2`相同的話則返回`#t`。
`(string-ref s idx)`
返回字符串`s`中索引為`idx`的字符(索引從0開始計數)。
`(string-set! s idx c)`
將字符串`s`中索引為`idx`的字符設置為`c`。
`(substring s start end)`
返回字符串`s`從`start`開始到`end-1`處的子串。例如`(substring "abcdefg" 1 4) => "b c d"`
`(string-append s1 s2 ...)`
連接兩個字符串`s1`和`s2`
`(string->list s)`
將字符串`s`轉換為由字符構成的表。
`(list->string ls)`
將一個由字符構成的表轉換為字符串。
`(string-copy s)`
復制字符串`s`。
> 練習1
>
> 編寫一個函數`title-style`,該函數用于將每個單詞的首字母大寫。
>
>
>
>
>
> ~~~
> (title-style "the cathedral and the bazaar")
> ;? "The Cathedral And The Bazaar"
> ~~~
>
>
>
>
## 11.4?小結
本章講解了字符和字符串。下章我將講解符號。符號是Lisp/Scheme中的一種字符型數據類型。使用這種數據類型,可以對文本進行快速操作。
## 11.5?習題解答
### 11.5.1?練習1
先將字符串轉化為表,將空格之后的字符大寫,最后將表轉換會字符串。【譯注:原文似有誤。】
~~~
(define (identity x) x)
(define (title-style str)
(let loop ((ls (string->list str))
(w #t)
(acc '()))
(if (null? ls)
(list->string (reverse acc))
(let ((c (car ls)))
(loop (cdr ls)
(char-whitespace? c)
(cons ((if w char-upcase identity) c) acc))))))
;;; Another answer, You can assign caps to the string.
(define (title-style str)
(let ((n (string-length str)))
(let loop ((w #t) (i 0))
(if (= i n)
str
(let ((c (string-ref str i)))
(if w (string-set! str i (char-upcase c)))
(loop (char-whitespace? c) (1+ i)))))))
(title-style "the cathedral and the bazaar")
;? "The Cathedral And The Bazaar"
~~~