- 读文件的汉字问题
1 |
|
字符串函数
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
60package main
import (
"fmt"
"strings"
)
func main1(){
str := "hello world"
value := strings.Contains(str, "hello")
if value{
fmt.Println(value)
fmt.Println("exist") // vaule为bool值,返回是否存在
}else{
fmt.Println(value)
fmt.Println("not found")
}
}
func main2(){
s:=[]string{"hello","world"}
str := strings.Join(s, " ") // 以分隔符" " 拼接字符串
fmt.Println(str)
}
func main3(){
str := "hello world"
i := strings.Index(str, "o") // 查找str中字符串"o"是否存在,存在返回索引,不存在返回-1
fmt.Println(i)
}
func main4 (){
str := "hello!"
s := strings.Repeat(str, 10) // 将字符串str重复10次
fmt.Println(s)
}
func main5(){
str := "hello"
s := strings.Replace(str, "l", "h", 1) // 输出为hehlo,将str中的l替换成h,从左向右开始扫描,替换一次
fmt.Println(s)
}
func main6(){
str := "hello world"
s := strings.Split(str, " ") // [hello world] 将字符串按分隔符" "分割,返回一个分割后的字符串切片
fmt.Println(s)
}
func main7(){
str := "---hello---world---"
s := strings.Trim(str, "---") //hello---world 去掉字符串前后的'---'字符串,类似于python的trip
fmt.Println(s)
}
func main(){
str := "hello world I am comming!"
s := strings.Fields(str) // [hello world I am comming!] 返回去掉字符串中空格后,有效字符串组成的字符串切片
fmt.Println(s)
}字符串类型转换
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
63package main
import (
"strconv"
"fmt"
)
func main0201() {
//1、将其他类型转成字符串
//将bool类型转成字符串
//s:=strconv.FormatBool(false)
//fmt.Println(s)
//2、将整型转成字符串
//formatInt(数据,进制) 二进制 八进制 十进制 十六进
//s:=strconv.FormatInt(123,10)
//s:=strconv.Itoa(123456)
//fmt.Println(s)
//3、浮点型转成字符串
//formatfloat(数据,'f',保留小数位置(谁四舍五入),位数(64 32))
s:=strconv.FormatFloat(1.155,'f',2,64)
fmt.Println(s)
}
func main0202(){
//1、将字符串转成bool
//str:="true"
////只能将“flase”“true”转成bool类型 有多余的数据 是无效的
//b,err:=strconv.ParseBool(str)
//if err!=nil{
// fmt.Println(err)
//}else {
// fmt.Println(b)
//}
//2、将字符串转成整型
//str:="1234"
//value,_:=strconv.ParseInt(str,10,64)
//fmt.Println(value)
//str:="123"
//value,_:=strconv.Atoi(str)
//fmt.Println(value)
//3、将字符串转成浮点型
//str:="12345"
//
//value,_:=strconv.ParseFloat(str,64)
//fmt.Println(value)
}
func main(){
b:=make([]byte,0,1024)
//将bool类型放在指定切片中
b=strconv.AppendBool(b,false)
b=strconv.AppendInt(b,123,10)
b=strconv.AppendFloat(b,1.234,'f',5,64)
b=strconv.AppendQuote(b,"hello")
fmt.Println(string(b))
}