Go strconv 包使用介绍

发布时间: 更新时间: 总字数:657 阅读时间:2m 作者: IP属地: 分享 复制网址

Golang 字符串转化介绍,字符串与其他类型相互转化主要在 strconv 包中,本文介绍使用方法,给出一个函数接口,然后匹配相关example。

strconv

字符串转换

字符串转化的函数在strconv中

  • Append* 函数表示将给定的类型(如bool, int等)转换为字符串后, 添加在现有的字节数组中[]byte
  • Format* 函数将给定的类型变量转换为string返回
  • Parse* 函数将字符串转换为其他类型,如:
    • strvonv.ParseBool(“true”)
// 字符串转整数
func Atoi(s string) (i int, err error)
// 整数值换字符串
func Itoa(i int) string
str := make([]byte, 0, 100)
str = strconv.AppendInt(str, 123, 10)  // 10用来表示进制, 此处为10进制
str = strconv.AppendBool(str, false)
str = strconv.AppendQuote(str, "andrew")
str = strconv.AppendQuoteRune(str, '刘')
fmt.Println(string(str))  // 123false"andrew"'刘'
s := strconv.FormatBool(true)
fmt.Printf("%T, %v\n", s, s)  // string, true
v := 3.1415926535
s32 := strconv.FormatFloat(v, 'E', -1, 32)
fmt.Printf("%T, %v\n", s32, s32)  // string, 3.1415927E+00
s10 := strconv.FormatInt(-44, 10)
fmt.Printf("%T, %v\n", s10, s10)  // string, -44
num := strconv.Itoa(1234)
fmt.Printf("%T, %v\n", s, s)  // int, 1023
fmt.Printf("%T, %v\n", num, num)  // string, 1234

字符串转数字示例

使用 Parse* 函数将字符串转换为其他类型

package main

import (
	"fmt"
	"strconv"
)

func ExampleStrconv() {
	// 字符串转化为 bool 类型
	if b, err := strconv.ParseBool("true"); err != nil {
		fmt.Println(err.Error())
	} else {
		fmt.Println(b)
	}

	// 字符串转化为 int
	if i, err := strconv.Atoi("18"); err != nil {
		fmt.Println(err.Error())
	} else {
		fmt.Println(i)
	}

	// 另一种方法,字符串转化为 int64,0x12 = 1*16 + 2 = 18
	if i64, err := strconv.ParseInt("12", 16, 64); err != nil {
		fmt.Println(err.Error())
	} else {
		fmt.Printf("%T %#v\n", i64, i64)
	}

	// 字符串转化为 float32, float 可能存在精度问题
	if f32, err := strconv.ParseFloat("3.14", 32); err != nil {
		fmt.Println(err.Error())
	} else {
		fmt.Println(f32)
	}

	// Output:
	//true
	//18
	//int64 18
	//3.14
}

其他类型转化为字符串

Format* 函数将给定的类型变量转换为string返回

package main

import (
	"fmt"
	"strconv"
)

func ExampleStrconf() {
	// 其他类型转字符串
	b := strconv.FormatBool(true)
	fmt.Printf("%T %#v\n", b, b)

	i := strconv.Itoa(18)
	fmt.Printf("%T %q\n", i, i)

	i10 := strconv.FormatInt(18, 16)
	fmt.Printf("%T %q\n", i10, i10)

	i64 := strconv.FormatFloat(3.1415926, 'E', -1, 64)
	fmt.Printf("%T %q\n", i64, i64)

	// Output:
	//string "true"
	//string "18"
	//string "12"
	//string "3.1415926E+00"
}

其他类型向字符串转化2

fmt.Sprintf 实现

package main

import "fmt"

func ExampleSprintf() {
	// 其他类型转字符串
	si := fmt.Sprintf("%d", 18)
	fmt.Printf("%T %#v\n", si, si)

	sf := fmt.Sprintf("%.2f", 3.1415926)
	fmt.Printf("%T %#v\n", sf, sf)

	// Output:
	//string "18"
	//string "3.14"
}
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数