Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > golang 标准库strconv

golang标准库strconv常用方法

作者:HotCoffee-GPS

在Go语言中,strconv 包提供了许多用于字符串和基本数据类型之间转换的函数,今天通过本文给大家介绍golang标准库strconv常用方法,感兴趣的朋友跟随小编一起看看吧

strconv 包是用来处理字符串和基本数据类型之间转换的。它提供了多种函数,用于将字符串转换为数字类型(如整型、浮点型等),以及将数字类型转换为字符串。

常用方法

字符串与数字转换

字符串转整数

// 字符串转 int
num, err := strconv.Atoi("123")           // 123, nil
num, err = strconv.Atoi("abc")            // 0, error
// 字符串转 int(指定进制和位数)
num64, err := strconv.ParseInt("123", 10, 64)    // int64 123, nil
num64, err = strconv.ParseInt("FF", 16, 64)      // int64 255, nil
num64, err = strconv.ParseInt("1010", 2, 64)     // int64 10, nil
// 字符串转 uint
u, err := strconv.ParseUint("123", 10, 64)       // uint64 123, nil

整数转字符串

// int 转字符串
str := strconv.Itoa(123)                  // "123"
// int64 转字符串(指定进制)
str = strconv.FormatInt(123, 10)          // "123" (10进制)
str = strconv.FormatInt(255, 16)          // "ff" (16进制)
str = strconv.FormatInt(10, 2)            // "1010" (2进制)
// uint64 转字符串
str = strconv.FormatUint(123, 10)         // "123"

字符串与浮点数转换

字符串转浮点数

// 字符串转 float64
f, err := strconv.ParseFloat("3.14", 64)         // float64 3.14, nil
f, err = strconv.ParseFloat("1.23e-4", 64)       // float64 0.000123, nil
f, err = strconv.ParseFloat("NaN", 64)           // float64 NaN, nil
f, err = strconv.ParseFloat("Inf", 64)           // float64 +Inf, nil

浮点数转字符串

// float64 转字符串
str := strconv.FormatFloat(3.14, 'f', 2, 64)     // "3.14"
str = strconv.FormatFloat(3.14159, 'f', -1, 64)  // "3.14159"
str = strconv.FormatFloat(3.14, 'e', 2, 64)      // "3.14e+00"
str = strconv.FormatFloat(123.456, 'E', -1, 64)  // "1.23456E+02"
// FormatFloat 格式说明:
// 'f': 普通小数格式 (-ddd.dddd)
// 'e': 科学计数法 (-d.dddde±dd)
// 'E': 科学计数法 (-d.ddddE±dd)
// 'g': 自动选择 %e 或 %f
// 'G': 自动选择 %E 或 %f

字符串与布尔值转换

字符串转布尔值

// 字符串转 bool
b, err := strconv.ParseBool("true")       // true, nil
b, err = strconv.ParseBool("1")           // true, nil
b, err = strconv.ParseBool("t")           // true, nil
b, err = strconv.ParseBool("TRUE")        // true, nil
b, err = strconv.ParseBool("false")       // false, nil
b, err = strconv.ParseBool("0")           // false, nil
b, err = strconv.ParseBool("f")           // false, nil
b, err = strconv.ParseBool("FALSE")       // false, nil
b, err = strconv.ParseBool("abc")         // false, error

布尔值转字符串

// bool 转字符串
str := strconv.FormatBool(true)           // "true"
str = strconv.FormatBool(false)          // "false"

引号处理

添加和去除引号

// 添加引号
quoted := strconv.Quote("Hello, 世界")    // `"Hello, 世界"`
quoted = strconv.Quote(`She said "hello"`) // `"She said \"hello\""`
// 添加 ASCII 引号(非ASCII字符转义)
quoted = strconv.QuoteToASCII("Hello, 世界") // `"Hello, \u4e16\u754c"`
// 添加字符引号
quoted = strconv.QuoteRune('世')          // `'世'`
quoted = strconv.QuoteRuneToASCII('世')   // `'\u4e16'`
// 去除引号
unquoted, err := strconv.Unquote(`"Hello"`)      // "Hello", nil
unquoted, err = strconv.Unquote(`'世'`)          // "世", nil
unquoted, err = strconv.Unquote("`raw string`")  // "raw string", nil

工具函数

带错误检查的转换

// 安全的字符串转整数
func SafeAtoi(s string, defaultValue int) int {
    if s == "" {
        return defaultValue
    }
    if num, err := strconv.Atoi(s); err == nil {
        return num
    }
    return defaultValue
}
// 安全的字符串转浮点数
func SafeParseFloat(s string, defaultValue float64) float64 {
    if s == "" {
        return defaultValue
    }
    if f, err := strconv.ParseFloat(s, 64); err == nil {
        return f
    }
    return defaultValue
}
// 使用
age := SafeAtoi("25", 0)          // 25
price := SafeParseFloat("19.99", 0.0) // 19.99
invalid := SafeAtoi("abc", -1)    // -1

进制转换工具

// 不同进制转换工具
func ConvertBase(num string, fromBase, toBase int) (string, error) {
    // 先转换为 int64
    n, err := strconv.ParseInt(num, fromBase, 64)
    if err != nil {
        return "", err
    }
    // 再转换为目标进制
    return strconv.FormatInt(n, toBase), nil
}
// 使用
result, _ := ConvertBase("255", 10, 16)   // "ff"
result, _ = ConvertBase("1010", 2, 10)    // "10"
result, _ = ConvertBase("FF", 16, 2)      // "11111111"

生成带引号的JSON值

func GenerateJSONString(value interface{}) string {
    switch v := value.(type) {
    case string:
        return strconv.Quote(v)
    case int:
        return strconv.Itoa(v)
    case float64:
        return strconv.FormatFloat(v, 'f', -1, 64)
    case bool:
        return strconv.FormatBool(v)
    default:
        return strconv.Quote(fmt.Sprintf("%v", v))
    }
}
// 使用
fmt.Println(GenerateJSONString("hello"))      // "\"hello\""
fmt.Println(GenerateJSONString(123))          // "123"
fmt.Println(GenerateJSONString(3.14))         // "3.14"
fmt.Println(GenerateJSONString(true))         // "true"

性能优化的数字转换

// 高性能的数字转字符串(避免内存分配)
type NumberBuffer struct {
    buf []byte
}
func (b *NumberBuffer) Reset() {
    b.buf = b.buf[:0]
}
func (b *NumberBuffer) AppendInt(n int) {
    b.buf = strconv.AppendInt(b.buf, int64(n), 10)
}
func (b *NumberBuffer) AppendFloat(f float64) {
    b.buf = strconv.AppendFloat(b.buf, f, 'f', 2, 64)
}
func (b *NumberBuffer) String() string {
    return string(b.buf)
}
// 使用
var buf NumberBuffer
buf.AppendInt(123)
buf.AppendFloat(45.67)
result := buf.String()  // "12345.67"

总结

到此这篇关于golang标准库strconv的文章就介绍到这了,更多相关golang 标准库strconv内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文