# 字串處理

字串在我們平常的 Web 開發中經常用到，包括使用者的輸入，資料庫讀取的資料等，我們經常需要對字串進行分割、連線、轉換等操作，本小節將透過 Go 標準函式庫中的 strings 和 strconv 兩個套件中的函式來講解如何進行有效快速的操作。

## 字串操作

下面這些函式來自於 strings 套件，這裡介紹一些我平常經常用到的函式，更詳細的請參考官方的文件。

* func Contains(s, substr string) bool

  字串 s 中是否包含 substr，回傳 bool 值

```go
fmt.Println(strings.Contains("seafood", "foo"))
fmt.Println(strings.Contains("seafood", "bar"))
fmt.Println(strings.Contains("seafood", ""))
fmt.Println(strings.Contains("", ""))
//Output:
//true
//false
//true
//true
```

* func Join(a \[]string, sep string) string

  字串連結，把 slice a 透過 sep 連結起來

```go
s := []string{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))
//Output:foo, bar, baz
```

* func Index(s, sep string) int

  在字串 s 中查詢 sep 所在的位置，回傳位置值，找不到回傳-1

```go
fmt.Println(strings.Index("chicken", "ken"))
fmt.Println(strings.Index("chicken", "dmr"))
//Output:4
//-1
```

* func Repeat(s string, count int) string

  重複 s 字串 count 次，最後回傳重複的字串

```go
fmt.Println("ba" + strings.Repeat("na", 2))
//Output:banana
```

* func Replace(s, old, new string, n int) string

  在 s 字串中，把 old 字串替換為 new 字串，n 表示替換的次數，小於 0 表示全部替換

```go
fmt.Println(strings.Replace("oink oink oink", "k", "ky", 2))
fmt.Println(strings.Replace("oink oink oink", "oink", "moo", -1))
//Output:oinky oinky oink
//moo moo moo
```

* func Split(s, sep string) \[]string

  把 s 字串按照 sep 分割，回傳 slice

```go
fmt.Printf("%q\n", strings.Split("a,b,c", ","))
fmt.Printf("%q\n", strings.Split("a man a plan a canal panama", "a "))
fmt.Printf("%q\n", strings.Split(" xyz ", ""))
fmt.Printf("%q\n", strings.Split("", "Bernardo O'Higgins"))
//Output:["a" "b" "c"]
//["" "man " "plan " "canal panama"]
//[" " "x" "y" "z" " "]
//[""]
```

* func Trim(s string, cutset string) string

  在 s 字串的頭部和尾部去除 cutset 指定的字串

```go
fmt.Printf("[%q]", strings.Trim(" !!! Achtung !!! ", "! "))
//Output:["Achtung"]
```

* func Fields(s string) \[]string

  去除 s 字串的空格符，並且按照空格分割回傳 slice

```go
fmt.Printf("Fields are: %q", strings.Fields("  foo bar  baz   "))
//Output:Fields are: ["foo" "bar" "baz"]
```

## 字串轉換

字串轉化的函式在 strconv 中，如下也只是列出一些常用的：

* Append 系列函式將整數等轉換為字串後，新增到現有的位元組陣列中。

```go
package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := make([]byte, 0, 100)
    str = strconv.AppendInt(str, 4567, 10)
    str = strconv.AppendBool(str, false)
    str = strconv.AppendQuote(str, "abcdefg")
    str = strconv.AppendQuoteRune(str, '單')
    fmt.Println(string(str))
}
```

* Format 系列函式把其他型別的轉換為字串

```go
package main

import (
    "fmt"
    "strconv"
)

func main() {
    a := strconv.FormatBool(false)
    b := strconv.FormatFloat(123.23, 'g', 12, 64)
    c := strconv.FormatInt(1234, 10)
    d := strconv.FormatUint(12345, 10)
    e := strconv.Itoa(1023)
    fmt.Println(a, b, c, d, e)
}
```

* Parse 系列函式把字串轉換為其他型別

```go
package main

import (
    "fmt"
    "strconv"
)
func checkError(e error){
    if e != nil{
        fmt.Println(e)
    }
}
func main() {
    a, err := strconv.ParseBool("false")
    checkError(err)
    b, err := strconv.ParseFloat("123.23", 64)
    checkError(err)
    c, err := strconv.ParseInt("1234", 10, 64)
    checkError(err)
    d, err := strconv.ParseUint("12345", 10, 64)
    checkError(err)
    e, err := strconv.Atoi("1023")
    checkError(err)
    fmt.Println(a, b, c, d, e)
}
```

## links

* [目錄](https://github.com/doggy8088/build-web-application-with-golang-zhtw/tree/4cbbaa31bdfc3678915eb91f23db2f1bad554a20/preface.md)
* 上一節: [檔案操作](/build-web-application-with-golang-zhtw/07.0/07.5.md)
* 下一節: [小結](/build-web-application-with-golang-zhtw/07.0/07.7.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://willh.gitbook.io/build-web-application-with-golang-zhtw/07.0/07.6.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
