国产chinesehdxxxx野外,国产av无码专区亚洲av琪琪,播放男人添女人下边视频,成人国产精品一区二区免费看,chinese丰满人妻videos

第十一章 字符與字符串

2018-02-24 15:45 更新

11.1?簡介

我只介紹了表和數(shù),因?yàn)樗鼈冊(cè)赟cheme中最為常用。然而,Scheme也有像字符(Character)、字符串(String)符號(hào)(Symbol)、向量(Vector)等的其它數(shù)據(jù)類型,我將在11到14章節(jié)中介紹它們。

11.2?字符

在某個(gè)字符前添加#\來表明該物是一個(gè)字符。例如,#\a表示字符a。字符#\Space、#\Tab#\Linefeed#\Return分別代表空格(Space)、制表符(Tab),Linefeed和返回(Return)。R5RS中定義了下面的與字符相關(guān)的函數(shù)。

(char? obj)

如果obj是一個(gè)字符則返回#t。

(char=? c1 c3)

如果c1和c2是同一個(gè)字符的話則返回#t

(char->integer c)

將c轉(zhuǎn)化為對(duì)應(yīng)的整數(shù)(字符代碼,character code)。示例:(char->integer #\a) => 97

(integer->char n)

該函數(shù)將一個(gè)整數(shù)轉(zhuǎn)化為對(duì)應(yīng)的字符。

(char<? c1 c2)

(char<= c1 c2)

(char> c1 c2)

(char>= c1 c2)

這些函數(shù)用于比較字符。實(shí)際上,這些函數(shù)比較的是字符代碼的大小。例如,(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)

這些比較函數(shù)對(duì)大小寫不敏感。

(char-alphabetic? c)

(char-numeric? c)

(char-whitespace? c)

(char-upper-case? c)

(char-lower-case? c)

這些函數(shù)分別用于檢測(cè)字符c是否為字母、數(shù)字、空白符、大寫字母或小寫字母。

(char-upcase c)

(char-downcase c)

這些函數(shù)分別返回字符C對(duì)應(yīng)的大寫或小寫。

11.3?字符串

字符串通過兩個(gè)閉合的雙引號(hào)表示。例如,”abc”表示字符串a(chǎn)bc。R5RS定義了下面的函數(shù)。

(string? s)

如果s是一個(gè)字符則返回#t。

(make-string n c)

返回由n個(gè)字符c組成的字符串。參數(shù)c可選。

(string-length s)

返回字符串s的長度。

(string=? s1 s2)

如果字符串s1s2相同的話則返回#t。

(string-ref s idx)

返回字符串s中索引為idx的字符(索引從0開始計(jì)數(shù))。

(string-set! s idx c)

將字符串s中索引為idx的字符設(shè)置為c。

(substring s start end)

返回字符串sstart開始到end-1處的子串。例如(substring "abcdefg" 1 4) => "b c d"

(string-append s1 s2 ...)

連接兩個(gè)字符串s1s2

(string->list s)

將字符串s轉(zhuǎn)換為由字符構(gòu)成的表。

(list->string ls)

將一個(gè)由字符構(gòu)成的表轉(zhuǎn)換為字符串。

(string-copy s)

復(fù)制字符串s。

練習(xí)1

編寫一個(gè)函數(shù)title-style,該函數(shù)用于將每個(gè)單詞的首字母大寫。

(title-style "the cathedral and the bazaar")
;? "The Cathedral And The Bazaar"

11.4?小結(jié)

本章講解了字符和字符串。下章我將講解符號(hào)。符號(hào)是Lisp/Scheme中的一種字符型數(shù)據(jù)類型。使用這種數(shù)據(jù)類型,可以對(duì)文本進(jìn)行快速操作。

11.5?習(xí)題解答

11.5.1?練習(xí)1

先將字符串轉(zhuǎn)化為表,將空格之后的字符大寫,最后將表轉(zhuǎn)換會(huì)字符串。【譯注:原文似有誤。】

(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"
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)