文章

golang学习记录(5)

字符串的基本操作

1、转义符

1.1、基本规则

通常在各种语言中转义符都是同一个:\,千万不要写反

举例:

1
2
name := "你可真是个\"小机灵鬼\""
//在这里直接使用"小机灵鬼"会报错,因为双引号是字符串的标志,所以需要使用转义符来表示引号:\"

1.2、常见的转义符

在golang中常用的转义符如下:

go

2、格式化输出

Println:表示输出换行 Print:表示输出不换行

2.1、基本使用

通常情况下使用平凑方法进行输出非常麻烦: go

使用格式化输出的方法–Printf:

1
fmt.Printf("用户名:%s, 年龄:%d,地址:%s, 电话:%s\r\n",username, age, address, mobile )

2.2、优缺点

优点:易读易维护

缺点:性能相对较低

2.3、进阶

2.3.1、缺省格式和类型

go

2.3.2、整形

go

2.3.3、字符

go

2.3.4、字符串

go

2.3.5、浮点数

go

3、字符串操作常用方法

3.1、计算字符串的长度

计算字符串的长度也有很多种情况

3.1.1、只有英文和数字

1
2
name := "hello world"
fmt.Println(len(name))

3.1.2、字符串中包含中文

1
2
3
name := "hello 世界"
bytes := []byte(name)
fmt.Println(len(bytes))

3.2、高性能字符串拼接

3.2.1、使用+号

1
username := "user" + "name"

3.2.2、在输出的时候通过格式化输出

1
2
fmt.Printf("用户名:%s, 年龄:%d,地址:%s, 电话:%s\r\n",username, age, address, mobile )

3.2.3、使用strings.Builder

这是一种高性能的方式

1
2
3
4
5
var builder strings.Builder
builder.WriteString("hello")
builder.WriteString("world")
result := builder.String()
fmt.Println(result)

3.3、字符串的比较

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//等于
a := "hello"
b := "hello"
fmt.Println(a == b)

//不等于
a = "hello"
b = "world"
fmt.Println(a != b)

//大于
a = "hello"
b = "world"
fmt.Println(a > b)

//小于
a = "hello"
b = "world"
fmt.Println(a < b)

//大于等于
//小于等于
//……

3.4、strings包里常用的方法

3.4.1、关于包的导入

1
2
3
4
import {
	"fmt"
	"strings"
}

3.4.2、常用方法

(1)、是否包含指定字符串

1
strings.Contains("hello world", "world")

(2)、字符串的长度

1
2
name := "hello world"
len(name)

(3)、查询字串出现的次数

1
strings.Count("hello world", "l")

(4)、分割字符串

1
2
//以空格为分隔符进行分割
strings.Split("hello world", " ")

(5)、字符串是否包含前后缀

1
2
3
4
5
//前缀
strings.HasPrefix("hello world", "he")

//后缀
strings.HasSuffix("hello world", "ld")

(6)、查询字串出现的位置

1
2
//英文
strings.Index("hello world", "lo")

(7)、字串替换

1
2
3
//把字符串里的所有l替换成a,替换前2个
//-1表示全部替换
strings.Replace("hello world", "l", "a", 2)

(8)、大小写转换

1
2
3
4
5
//全转成小写
strings.ToLower("HELLO WORLD")

//全转成大写
strings.ToUpper("hello world")

(9)、去掉特殊字符

1
2
3
4
5
6
7
8
9
10
11
//去掉左右两边指定的字符,指定的字符可以是多个,比如空格,#,*等
strings.Trim("#hello #world#", "#")
//得到的结果是:hello #world

//左边的特殊字符
strings.TrimLeft("#hello #world#", "#")
//得到的结果是:hello #world#

//右边的特殊字符
strings.TrimRight("#hello #world#", "#")
//得到的结果是:#hello #world

更多方法可以查看源码,在ide中点击显示的函数可以直接转换到源码

本文由作者按照 CC BY 4.0 进行授权