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

栏目: Go · 发布时间: 6年前

// 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
}

以上所述就是小编给大家介绍的《Go语言的字符串转换的处理一之strconv包》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Practical Vim, Second Edition

Practical Vim, Second Edition

Drew Neil / The Pragmatic Bookshelf / 2015-10-31 / USD 29.00

Vim is a fast and efficient text editor that will make you a faster and more efficient developer. It’s available on almost every OS, and if you master the techniques in this book, you’ll never need an......一起来看看 《Practical Vim, Second Edition》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

SHA 加密
SHA 加密

SHA 加密工具