strings 套件提供了處理字串的函式。
以下是這個套件中的部分函式;想看其他函式,請參閱文件!
| 作用 | 函式 | 用途 |
|---|---|---|
| 大小寫轉換 | ToLower | 將字串轉成小寫 |
| 大小寫轉換 | ToUpper | 將字串轉成大寫 |
| 搜尋 | Contains | 檢查字串是否包含特定子字串 |
| 搜尋 | Count | 計算子字串不重疊出現的次數 |
| 搜尋 | HasPrefix | 檢查字串是否以特定子字串開頭 |
| 搜尋 | HasSuffix | 檢查字串是否以特定子字串結尾 |
| 搜尋 | Index | 回傳子字串第一次出現的索引,找不到則回傳 -1 |
| 修改 | Replace | 取代最多 n 次出現的子字串 |
| 修改 | ReplaceAll | 取代所有出現的子字串 |
| 修改 | TrimSpace | 移除開頭與結尾的空白 |
| 拆分與合併 | Fields | 依空白將字串拆分成單字 |
| 拆分與合併 | FieldsSeq | 一次取得一個單字 |
| 拆分與合併 | Join | 用分隔符號連接字串切片 |
| 拆分與合併 | Split | 依分隔符號將字串拆成多個部分 |
| 拆分與合併 | SplitSeq | 一次取得一個部分 |
import (
"fmt"
"strings"
)
// Case conversion
strings.ToLower("Gopher") // "gopher"
strings.ToUpper("Gopher") // "GOPHER"
// Searching
strings.Contains("Apple", "le") // true
strings.Index("Apple", "le") // 3
strings.Index("Apple", "xyz") // -1
strings.Count("test", "t") // 2
strings.HasPrefix("Gopher", "Go") // true
strings.HasSuffix("Gopher", "er") // true
// Modifying
strings.TrimSpace(" hello ") // "hello"
strings.Replace("aabbcc", "b", "x", 1) // "aaxbcc"
strings.ReplaceAll("aabbcc", "b", "x") // "aaxxcc"
// Splitting or Joining
strings.Fields(" a b\tc ") // []string{"a", "b", "c"}
strings.Split("a,b,c", ",") // []string{"a", "b", "c"}
strings.Join([]string{"a", "b", "c"}, ",") // "a,b,c"
// You do not need to worry about this range syntax yet.
// It is covered later in the range iteration concept.
for word := range strings.FieldsSeq(" a b\tc ") {
fmt.Println(word)
}
// Output:
// a
// b
// c
for part := range strings.SplitSeq("a,b,c", ",") {
fmt.Println(part)
}
// Output:
// a
// b
// c