Golang语言字符串处理函数包strings,字符串类型转换包strconv。

示例代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* Golang语言字符串处理函数包strings,字符串类型转换包strconv
*/
package main

import (
"fmt"
"strconv"
"strings"
)

func main() {
str := "This is an example of a string"
fmt.Printf("Ture/False? Does the string \"%s\" have prefix %s?", str, "Th")
// 判断字符串的前缀
fmt.Printf("%t\n", strings.HasPrefix(str, "Th"))
fmt.Printf("True/False? Does the string \"%s\" have suffix %s?", str, "ing")
// 判断字符串的后缀
fmt.Printf("%t\n", strings.HasSuffix(str, "ing"))
fmt.Printf("True/False? Does the string \"%s\" have %s?", str, "xa")
// 判断字符串是否包含某字符
fmt.Printf("%t\n", strings.Contains(str, "xa"))
// 判断指定字符在字符串第一次出现的位置
fmt.Printf("%d\n", strings.Index(str, "s"))
// 判断指定字符在字符串最后一次出现的位置
fmt.Printf("%d\n", strings.LastIndex(str, "s"))
// 将字符串中的前n个字符替换,并返回一个新字符串,如果n=-1则替换所有字符串中的字符
fmt.Printf("%s\n", strings.Replace(str, "is", "at", 1))
// 统计指定字符在字符串中出现的次数
fmt.Printf("%d\n", strings.Count(str, "s"))
// 将字符串重复n次,并返回新字符串
fmt.Printf("%s\n", strings.Repeat(str, 2))
// 将字符串全部转换为小写字符
fmt.Printf("%s\n", strings.ToLower(str))
// 将字符串全部转换为大写字符
fmt.Printf("%s\n", strings.ToUpper(str))
// 去除字符串开头和结尾的空格
str1 := " This is an example of a string "
fmt.Printf("%s\n", strings.TrimSpace(str1))
// 去除字符串开头和结尾的指定字符,只去除字符串开头或结尾的指定字符
str2 := "my name is frank, this pencil is my"
fmt.Printf("%s\n", strings.Trim(str2, "my"))
fmt.Printf("%s\n", strings.TrimLeft(str2, "my"))
fmt.Printf("%s\n", strings.TrimRight(str2, "my"))
// 分割字符串,转换为一个slice
// 利用1个或多个空白字符来作为分隔符,将字符串分割成若干小块,并返回一个slice
// 如果字符串只包含空白字符串,则返回一个长度为0的slice
sli := strings.Fields(str)
for _, value := range sli {
fmt.Println(value)
}
str3 := "2019-05-07"
sli2 := strings.Split(str3, "-")
for _, value := range sli2 {
fmt.Println(value)
}
// 拼接slice元素成为一个字符串
fmt.Printf("%s\n", strings.Join(sli2, "-"))
// 字符串类型转换
str4 := "123"
// 字符串类型转换为int
num, _ := strconv.Atoi(str4)
fmt.Printf("%d\n", num)
// int转换为字符串类型
newStr4 := strconv.Itoa(num)
fmt.Printf("%s\n", newStr4)
}
运行结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Ture/False? Does the string "This is an example of a string" have prefix Th?true
True/False? Does the string "This is an example of a string" have suffix ing?true
True/False? Does the string "This is an example of a string" have xa?true
3
24
That is an example of a string
3
This is an example of a stringThis is an example of a string
this is an example of a string
THIS IS AN EXAMPLE OF A STRING
This is an example of a string
name is frank, this pencil is
name is frank, this pencil is my
my name is frank, this pencil is
This
is
an
example
of
a
string
2019
05
07
2019-05-07
123
123