字符串一般使用””来表示

strings 包的使用

Go 中使用 strings 包来完成对字符串的主要操作。

strings.Contains

检查子字符串是否存在于字符串中。

1
2
3
4
5
6
7
8
9
10
package main

import (
"fmt"
"strings"
)

func main() {
fmt.Println(strings.Contains("hello, world", "world")) // true
}

strings.Count

计算子字符串在字符串中非重叠的出现次数。

1
2
3
4
5
6
7
8
9
10
package main

import (
"fmt"
"strings"
)

func main() {
fmt.Println(strings.Count("cheese", "e")) // 3
}

strings.HasPrefix

检查字符串是否以指定前缀开头。

1
2
3
4
5
6
7
8
9
10
package main

import (
"fmt"
"strings"
)

func main() {
fmt.Println(strings.HasPrefix("hello, world", "hello")) // true
}

strings.HasSuffix

检查字符串是否以指定后缀结尾。

1
2
3
4
5
6
7
8
9
10
package main

import (
"fmt"
"strings"
)

func main() {
fmt.Println(strings.HasSuffix("hello, world", "world")) // true
}

strings.Index

查找子字符串在字符串中首次出现的索引。

1
2
3
4
5
6
7
8
9
10
package main

import (
"fmt"
"strings"
)

func main() {
fmt.Println(strings.Index("hello, world", "world")) // 7
}

strings.Join

将字符串切片用指定的分隔符连接成一个字符串。

1
2
3
4
5
6
7
8
9
10
11
package main

import (
"fmt"
"strings"
)

func main() {
slice := []string{"this", "is", "a", "dog"}
fmt.Println(strings.Join(slice, " ")) // "this is a dog"
}

strings.Replace

将子字符串替换为另一个子字符串。

1
2
3
4
5
6
7
8
9
10
package main

import (
"fmt"
"strings"
)

func main() {
fmt.Println(strings.Replace("hello, world", "world", "Go", 1)) // "hello, Go"
}

strings.Split

将字符串按指定的分隔符拆分成子字符串切片。

1
2
3
4
5
6
7
8
9
10
package main

import (
"fmt"
"strings"
)

func main() {
fmt.Println(strings.Split("a,b,c", ",")) // ["a", "b", "c"]
}

strings.ToLower

将字符串转换为小写。

1
2
3
4
5
6
7
8
9
10
package main

import (
"fmt"
"strings"
)

func main() {
fmt.Println(strings.ToLower("HELLO, WORLD")) // "hello, world"
}

strings.ToUpper

将字符串转换为大写。

1
2
3
4
5
6
7
8
9
10
package main

import (
"fmt"
"strings"
)

func main() {
fmt.Println(strings.ToUpper("hello, world")) // "HELLO, WORLD"
}

strconv 包的使用

strconv 包主要用于字符串和其他格式之间的互转

strconv.Atoi

将字符串转换为整数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import (
"fmt"
"strconv"
)

func main() {
i, err := strconv.Atoi("123")
if err != nil {
fmt.Println(err)
} else {
fmt.Println(i) // 123
}
}

strconv.Itoa

将整数转换为字符串。

1
2
3
4
5
6
7
8
9
10
11
package main

import (
"fmt"
"strconv"
)

func main() {
str := strconv.Itoa(123)
fmt.Println(str) // "123"
}

strconv.ParseFloat

将字符串转换为浮点数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import (
"fmt"
"strconv"
)

func main() {
f, err := strconv.ParseFloat("123.45", 64)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(f) // 123.45
}
}

strconv.FormatFloat

将浮点数转换为字符串。

1
2
3
4
5
6
7
8
9
10
11
package main

import (
"fmt"
"strconv"
)

func main() {
str := strconv.FormatFloat(123.45, 'f', 2, 64)
fmt.Println(str) // "123.45"
}

strconv.ParseInt

将字符串转换为整数,支持指定进制。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import (
"fmt"
"strconv"
)

func main() {
i, err := strconv.ParseInt("123", 10, 64)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(i) // 123
}
}