NotePublic/Software/Development/Language/Go/Basic/Golang_字符串操作.md

58 lines
2.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Golang 字符串操作
## 1.分割/拼接操作
```go
// 1. 以 "," 对字符串分割
s:="A,B,C"
parts:=strings.Split(s,",")
fmt.Println(parts)
// 2. 把字符串连接起来
s=strings.Join(parts,"-")
fmt.Println(s)
```
## 2.字符串和其他类型转换
```go
// 数字转字符串
s=strconv.Itoa(10)
fmt.Println(s)
// 字符串转整形
fmt.Println(strconv.Atoi(s))
```
## 3. 字符串查找
```go
strings.Contains("widuu", "id") // 查找某个字符是否在这个字符串中存在, return true
strings.Contains("id", "widuu") // 查找某个字符是否在这个字符串中存在, return false
strings.Contains("widuu", "i&d") // 查找某个字符是否在这个字符串中存在, return false
strings.ContainsAny("widuu", "i&d") // 查询字符串中是否包含多个字符, return true
strings.Count("widuu", "uu") // 在一段字符串中有多少匹配到的字符, return 1
strings.Count("widuu", "u") // 在一段字符串中有多少匹配到的字符, return 2
strings.Index("widuu", "i") // 查找字符串, 然后返回当前的位置, return 1
strings.Index("widuu", "u") // 查找字符串, 然后返回当前的位置, return 3
strings.LastIndex("widuu", "u") // 查找字符串, 然后返回最后出现的位置, return 4
strings.IndexAny("hello world hello world", "wo") // 查找字符串, 然后返回当前的位置, return 4
strings.LastIndexAny("hello world hello world", "wo") // 查找字符串, 然后返回最后出现的位置, return 19
```
## 4. 剔除字符
```go
strings.TrimSpace(" He llo ") // 剔除前后空格return "He llo"
strings.Trim("+He+llo++", "+") // 剔除前后指定字符return "He+llo"
strings.TrimLeft("+-+-He+-llo+-+-", "+-") // 剔除左侧任意匹配字符return "He+-llo+-+-"
strings.TrimRight("+-+-He+-llo+-+-", "+-") // 剔除右侧任意匹配字符return "+-+-He+-llo"
strings.TrimPrefix("+-+-He+-llo+-+-", "+-") // 仅剔除一组完全匹配的前导符return "+-He+-llo+-+-"
strings.TrimSuffix("+-+-He+-llo+-+-", "+") // 仅剔除一组完全匹配的后导符return "+-+-He+-llo+-"
```
## 4.字符串长度
```go
fmt.Println(len("Hello"))
```