go std strconv
strconv 是一个提供了字符串和其他基本类型相互转换的包
一般情况下,其他基本类型向 string 转换不会返回 error
而在 string 转向其他类型的时候,需要处理可能返回的 error
int <--> string 最简便的一种
var num0 int
var str0 string
init(num, str)
// int to string
str := strconv.ItoA(num0) // int 向 string 转换不返回 error
// string to int
num, err := strconv.Atoi(str0) // string 转向其他类型需要处理返回的 error
if err != nil {}
其他类型的转化具有一定的规律:
- string 转向其他类型
ParseXxxx()需要处理 error - 其他类型转向 string
FormatXxxx()不需要处理 error
Format -> string
s := strconv.FormatBool(true) // 将返回 "true"
s := strconv.FormatFloat(3.1415, 'E', -1, 64) //
s := strconv.FormatInt(-42, 16) // 指定转换后的进制,这里指定为16,即转换成16进制形式的 string
s := strconv.FormatUint(42, 16)
Parse -> 其他类型
b, err := strconv.ParseBool("true")
f, err := strconv.ParseFloat("3.1415", 64)
i, err := strconv.ParseInt("-42", 10, 64)
u, err := strconv.ParseUint("42", 10, 64)
Quote/QuoteXxx 在字符串或者字符前后加引号
s := "Hello, world! 你好,世界!"
word := '我'
s0 := strconv.Quote(s) // 在字符串前后加引号
s1 := strconv.QuoteToASCII(s) // 加引号,非 ascii 则进行编码
s3 := strconv.QuoteRune(word) // 在 Rune 前后加引号
结果:
"Hello, world! 你好,世界!"
"Hello, world! \u4f60\u597d\uff0c\u4e16\u754c\uff01"
'我'
浙公网安备 33010602011771号