在 Elm 中,字元和字串是表示文字的基礎。
字串可以想成是一串字元,而大多數List函式在String模組中都有對應的版本。
Char型別代表以單引號括住的單一 unicode 字元,例如'a'。
Char模組提供述詞函式(Char -> Bool)來測試字元的性質:isUpper、isLower、isAlpha和isAlphaNum。
這個模組也提供轉換字元的函式toUpper、toLower、toLocaleUpper、toLocaleLower,以及透過toCode和fromCode在其數值 unicode 值(Int)之間互相轉換。
String型別提供內建的表示方式,能有效率地操作字串,並可表示任何 unicode 字元序列,例如 "this is an Elm string."
多行字串以三個雙引號表示,可以包含未跳脫的引號和換行。
"""
This is a multiline string.
All line-breaks and whitespace,
are preserved.
"""
String模組包含下方表格中彙整的所有函式。
一些最常使用的函式包括:
cons : Char -> String -> String會在字串開頭加上一個字元。
cons 'T' "he truth is out there"
--> "The truth is out there"
(++): String -> String -> String會串接兩個字串。
"butter" ++ "fly"
--> "butterfly"
split : String -> String -> List String會在指定的分隔符號處把字串拆成字串陣列。
split ";" "cat;dog;cow"
--> ["cat", "dog", "cow"]
join : String -> List String -> String會用指定的分隔符號把字串陣列串接起來。
join "a" ["H", "w", "ii", "n"]
--> "Hawaiian"
replace : String -> String -> String -> String會取代指定子字串的所有出現位置。
replace "Hello" "Goodbye cruel" "Hello world."
--> "Goodbye cruel world."
length : String -> Int會回傳字串中的字元數。
length "Hello world."
--> 12
toInt : String -> Maybe Int會嘗試把字串轉成Just Int,格式不正確的字串則回傳Nothing。
toInt "-42"
--> Just -42
contains : String -> String -> Bool會檢查第二個字串是否包含第一個字串。
contains "the" "theory"
--> True
map : (Char -> Char) -> String -> String會把指定的函式套用到字串中的每個Char。
請注意,提供的函式必須是Char到Char的對應。
map (\c -> if c == '/' then '.' else c) "a/b/c"
--> "a.b.c"
| 操作 | 子字串 | 檢查 | 轉換 | 高階 |
|---|---|---|---|---|
reverse |
slice |
length |
toInt |
map |
repeat |
left |
isEmpty |
fromInt |
filter |
replace |
right |
contains |
toFloat |
foldl |
append |
dropLeft |
startsWith |
fromFloat |
foldr |
concat |
dropRight |
indexes |
toList |
any |
split |
fromList |
all |
||
join |
fromChar |
|||
words |
||||
lines |
||||
cons |
||||
uncons |
在這個練習中,你將實作一部分的工具函式,協助開發者清理識別字名稱。
在這 5 個任務中,你會逐步打造出clean函式。
有效的識別字由零個或多個字母與底線組成。
如果傳入clean函式的是一個空字串,就應該回傳空字串。
實作clean1函式,將任何空格替換為底線。開頭與結尾的空格也一樣要處理。
clean1 "my Id"
--> "my___Id"
實作clean2,做到前一個函式的所有事情,並將常見的控制字元(\n、\t 和 \r)替換為字串"[CTRL]"。
clean2 "my\nId"
--> "my[CTRL]Id",
實作clean3,做到前一個函式的所有事情,並將 kebab-case 轉換成 camelCase。
clean3 "à-ḃç"
--> "àḂç"
實作clean4,做到前一個函式的所有事情,並省略所有數字。
clean4 "123"
--> ""
最後,實作clean,做到前一個函式的所有事情,並省略範圍從 'α' 到 'ω' 的希臘字母。
clean "My Οβιεγτ Finder"
--> "My_Ο_Finder"