Go之int整数与string字符串相互转换

文章目录

  1.int整数转字符串
    1.1fmt.Sprintf
    1.2strconv.Itoa
    1.3strconv.FormatIntgit

  2.字符串转int整数
    2.1strconv.Atoi
    2.2strconv.ParseInt学习


1.int整数转字符串

1.1 fmt.Sprintf

fmt 包应该是最多见的了,从刚开始学习 Golang 就接触到了,写 ‘hello, world' 就得用它。它还支持格式化变量转为字符串。%d 表明十进制整数。spa

//Sprintf formats according to a format specifier and returns the resulting string.
func Sprintf(format string, a ...interface{}) string 复制代码

使用示例:code

str := fmt.Sprintf("%d", a)
复制代码

1.2 strconv.Itoa

支持 int 类型转换成字符串orm

//Itoa is shorthand for FormatInt(int64(i), 10).
func Itoa(i int) string 复制代码

使用示例:ci

str := strconv.Itoa(a)
复制代码

1.3 strconv.FormatInt

支持 int64 类型转换成字符串 参数 i 是要被转换的整数, base 是进制,例如2进制,支持2到36进制。字符串

//FormatInt returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters ‘a' to ‘z' for digit values >= 10.
func FormatInt(i int64, base int) string 复制代码

使用示例:string

str := strconv.FormatInt(a, 10)
复制代码

2.字符串转int整数

2.1 strconv.Atoi

比较常见的方法it

// Atoi returns the result of ParseInt(s, 10, 0) converted to type int.
func Atoi(s string) (int, error) 复制代码

使用示例:io

i,err := strconv.Atoi(a)
复制代码

2.2 strconv.ParseInt

功能很是强大

// ParseInt interprets a string s in the given base (0, 2 to 36) and
// bit size (0 to 64) and returns the corresponding value i.
func ParseInt(s string, base int, bitSize int) (i int64, err error) 复制代码

参数1 数字的字符串形式 参数2 数字字符串的进制 好比二进制 八进制 十进制 十六进制 参数3 返回结果的bit大小 也就是int8 int16 int32 int64

使用示例:

i, err := strconv.ParseInt("123", 10, 32)
复制代码
相关文章
相关标签/搜索