美文网首页一个程序猿的奋斗史php开发golang
Go语言学习笔记17.字符串和json处理

Go语言学习笔记17.字符串和json处理

作者: 快乐的提千万 | 来源:发表于2019-11-07 10:46 被阅读0次

    字符串处理

    这里只展示了常用的,更多的可以去看文档。文档地址在第一篇里面有。

    func Contains(s, substr string) bool
    功能:字符串s中是否包含substr,返回bool值
    fmt.Println(strings.Contains("seafood", "foo"))
    
    func Join(a []string, sep string) string
    功能:字符串链接,把slice a通过sep链接起来
    s := []string{"foo", "bar", "baz"}
    fmt.Println(strings.Join(s, ", "))
    //运行结果:foo, bar, baz
    
    func Split(s, sep string) []string
    功能:把s字符串按照sep分割,返回slice
    fmt.Printf("%q\n", strings.Split("a,b,c", ","))
    //["a" "b" "c"]
    
    func Index(s, sep string) int
    功能:在字符串s中查找sep所在的位置,返回位置值,找不到返回-1
    fmt.Println(strings.Index("chicken", "ken"))
    
    func Repeat(s string, count int) string
    功能:重复s字符串count次,最后返回拼接好的字符串
    fmt.Println("ba" + strings.Repeat("na", 2))
    //运行结果:banana
    
    func Replace(s, old, new string, n int) string
    功能:在s字符串中,把old字符串替换为new字符串,n表示替换的次数,小于0表示全部替换
    fmt.Println(strings.Replace("oink oink oink", "oink", "moo", -1))
    
    func Trim(s string, cutset string) string
    功能:在s字符串的头部和尾部去除cutset指定的字符串
    fmt.Printf("[%q]", strings.Trim(" !!! Achtung !!! ", "! "))
    //运行结果:["Achtung"]
    
    func Fields(s string) []string
    功能:去除s字符串的空格符,并且按照空格分割返回slice
    fmt.Printf("Fields are: %q", strings.Fields("  foo bar  baz   "))
    //运行结果:Fields are: ["foo" "bar" "baz"]
    

    字符串转换

    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 系列函数把其他类型的转换为字符串。
    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 系列函数把字符串转换为其他类型。
    a, err := strconv.ParseBool("false")
    b, err := strconv.ParseFloat("123.23", 64)
    c, err := strconv.ParseInt("1234", 10, 64)
    d, err := strconv.ParseUint("12345", 10, 64)
    e, err := strconv.Atoi("1023")
    fmt.Println(a, b, c, d, e) //false 123.23 1234 12345 1023
    

    正则表达式

    package main
    
    import (
        "fmt"
        "regexp"
    )
    
    func main() {
    
        buf := "abc azc a7c aac 888 a9c  tac a9c"
    
        //1) 解释规则, 它会解析正则表达式,如果成功返回解释器
        reg2 := regexp.MustCompile(`a.c`)
        fmt.Println("reg2 = ",reg2) //reg2 =  a.c
        reg3 := regexp.MustCompile(`a[0-9]c`)
        fmt.Println("reg3 = ",reg3)//reg3 =  a[0-9]c
    
        reg1 := regexp.MustCompile(`a\dc`)
        if reg1 == nil { //解释失败,返回nil
            fmt.Println("regexp err")
            return
        }
    
        //2) 返回符合规则的[]string切片,如果没有匹配到,会返回nil。
        result1 := reg1.FindAllStringSubmatch(buf, -1)
        fmt.Println("result1 = ", result1)//[[a7c] [a9c] [a9c]]
    
        result2 := reg1.FindAllString(buf, -1) 
        fmt.Println("result2 = ", result2)//[a7c a9c a9c]
    
    }
    
    在这里插入图片描述

    json

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    //首字母是大写才会被输出
    type IT struct {
        Company  string   `json:"-"`        //此字段不会输出到屏幕
        Subjects []string `json:"subjects"` //二次编码
        IsOk     bool     `json:",string"`  //会转换成string再输出到json
        Price    float64  `json:",string"`
        Type     int      `json:",omitempty"`//为空则不会输出
    }
    
    func main() {
        
        s := IT{"itcast", []string{"Go", "C++", "Python", "Test"}, true, 666.666,0}
    
        //编码,根据内容生成json文本
        buf, err := json.Marshal(s) //生成一段JSON格式的文本
        if err != nil {
            fmt.Println("err = ", err)
            return
        }
        fmt.Println("buf = ", string(buf)) 
        //buf =  {"subjects":["Go","C++","Python","Test"],"IsOk":"true","Price":"666.666"}   注意没有type
    
        s2 := IT{"itcast", []string{"Go", "C++", "Python", "Test"}, true, 666.666,1}
    
        buf2, err := json.MarshalIndent(s2, "", "   ") //格式化编码
        if err != nil {
            fmt.Println("err = ", err)
            return
        }
        fmt.Println("buf = ", string(buf2))
        /**
        buf =  {
            "subjects": [
                    "Go",
                    "C++",
                    "Python",
                    "Test"
            ],
            "IsOk": "true",
            "Price": "666.666",
            "Type": 1
        }
        */
    
    }
    

    map转json:

    func main() {
        //创建一个map
        m := make(map[string]interface{}, 4)
        m["company"] = "itcast"
        m["subjects"] = []string{"Go", "C++", "Python", "Test"}
        m["isok"] = true
        m["price"] = 666.666
    
        //编码成json
        //result, err := json.Marshal(m)
        result, err := json.MarshalIndent(m, "", "  ")
        if err != nil {
            fmt.Println("err = ", err)
            return
        }
        fmt.Println("result = ", string(result))
    }
    

    json转结构体

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type IT struct {
        Company  string   `json:"company"`
        Subjects []string `json:"subjects"` //二次编码
        IsOk     bool     `json:"isok"`
        Price    float64  `json:"price"`
    }
    
    type IT2 struct {
        Subjects []string `json:"subjects"` //二次编码
    }
    
    func main() {
    
        jsonBuf := `
                {
                "company": "itcast",
                "subjects": [
                    "Go",
                    "C++",
                    "Python",
                    "Test"
                ],
                "isok": true,
                "price": 666.666
            }`
    
        var tmp IT                                   //定义一个结构体变量
        err := json.Unmarshal([]byte(jsonBuf), &tmp) //第二个参数要地址传递
        if err != nil {
            fmt.Println("err = ", err)
            return
        }
        fmt.Printf("tmp = %+v\n", tmp) //tmp = {Company:itcast Subjects:[Go C++ Python Test] IsOk:true Price:666.666}
    
        //只接受部分数据
        var tmp2 IT2
        err = json.Unmarshal([]byte(jsonBuf), &tmp2) //第二个参数要地址传递
        if err != nil {
            fmt.Println("err = ", err)
            return
        }
        fmt.Printf("tmp2 = %+v\n", tmp2)
    
    }
    
    

    json转map

        m := make(map[string]interface{}, 4)
    
        err := json.Unmarshal([]byte(jsonBuf), &m) //第二个参数要地址传递
        if err != nil {
            fmt.Println("err = ", err)
            return
        }
        fmt.Printf("m = %+v\n", m) //m = map[company:itcast isok:true price:666.666 subjects:[Go C++ Python Test]]
    

    相关文章

      网友评论

        本文标题:Go语言学习笔记17.字符串和json处理

        本文链接:https://www.haomeiwen.com/subject/ejkebctx.html