Go语言的字符串转换的处理一之strconv包

// code_028_strings_strconv project main.go
package main

import (
    "fmt"
    "strconv"
)

//strings和strconv包中的函数--->>>
//strings包,字符处理:Contains,Join,Index,Repeat,Replace,Split,Trim, Fields
//strconv包,字符转换:
//1) Append添加字符串元素:AppendInt,AppednBool,AppendQuote, AppendQuoteRune
//2) Format格式化程字符串:FormatBool(false),FormatInt(1234, 10),FormatUint(12345, 10),Itoa(1023)
//3) Parse字符串转换为其他类型:ParseBool("false"),ParseFloat("123.23", 64),ParseInt("1234", 10, 64),ParseUint("12345", 10, 64),Atoi("1023")
//    返回值value, err := strconv.ParseBool("false")

func checkError(e error) {
    if e != nil {
        fmt.Println(e)
    }
}

func main() {

    //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的使用
    a2 := strconv.FormatBool(false)
    b2 := strconv.FormatInt(1234, 10)
    c2 := strconv.FormatUint(12345, 10)
    d2 := strconv.Itoa(1023)

    fmt.Println(a2, b2, c2, d2) //false 1234 12345 1023

    //Parse的使用
    a3, err := strconv.ParseBool("false")
    checkError(err)
    b3, err := strconv.ParseFloat("123.23", 64)
    checkError(err)
    c3, err := strconv.ParseInt("1234", 10, 64)
    checkError(err)
    d3, err := strconv.ParseUint("12345", 10, 64)
    checkError(err)
    e3, err := strconv.Atoi("1023")
    checkError(err)
    fmt.Println(a3, b3, c3, d3, e3) //false 123.23 1234 12345 1023
}

猜你喜欢

转载自blog.51cto.com/13914991/2294102