文本、文件處理
一、 字符串處理
- Go標準庫中的strings和strconv
1. 字符串操作
Contains
func Contains(s, substr string) bool
- 功能:字符串s中是否包含substr,返回bool值
Join
func Join(a []string, sep string) string
- 字符串連接,把slice a 通過sep連接起來
Index
func Index(s, sep string) int
- 在字符串s中查找sep所在的位置,返回位置值,找不到返回-1
Repeat
func Reprat(s string, count int) string
- 重複s字符串count次,最後返回重複的字符串
Replace
func Replace(s, old, new string, n int) string
- 在s字符串中, 把old字符串替換爲new字符串,n表示替換的次數,小於0表示全部替換
Splic
Trim
func Trim(s string, cutset) string
- 在s字符串的頭部和尾部去除cutset指定的字符串
Fields
func Fields(s string) []string
- 去除s字符串的空格符, 並且按照空格分割返回slice
2. 字符串轉換
Append
- Append 系列函數將整數等轉換爲字符串後,添加到現有的字節數組中
str := make([]byte, 0, 100)
str = strconv.AppendInt(str, 4567, 10) //以10進制方式追加
str = strconv.AppendBool(str, false)
str = strconv.AppendQuote(str, "abcdefg")
str = strconv.AppendQuoteRune(str, '單')
fmt.Println(string(str)) //4567false"abcdefg"'單'
Format
Format 系列函數把其他類型的轉換爲字符串
a := strconv.FormatBool(false)
b := strconv.FormatInt(1234, 10)
c := strconv.FormatUint(12345, 10)
d := strconv.Itoa(1023)
fmt.Println(a, b, c, d) //false 1234 12345 1023
Parse
Parse 系列函數把字符串轉換爲其他類型。
package main
import (
"fmt"
"strconv"
)
func checkError(e error) {
if e != nil {
fmt.Println(e)
}
}
func main() {
a, err := strconv.ParseBool("false")
checkError(err)
b, err := strconv.ParseFloat("123.23", 64)
checkError(err)
c, err := strconv.ParseInt("1234", 10, 64)
checkError(err)
d, err := strconv.ParseUint("12345", 10, 64)
checkError(err)
e, err := strconv.Atoi("1023")
checkError(err)
fmt.Println(a, b, c, d, e) //false 123.23 1234 12345 1023
}
3. json
- 內置encoding/json 標準庫
1. 編碼json
2. 解碼json
4. 文件操作
注:該筆記是本人通過學習視頻,做的學習筆記~