Sharing of efficient methods for converting Golang characters to integers

王林
Release: 2024-04-03 15:36:02
Original
642 people have browsed it

Go 中将字符高效转换为整型的指南:使用 strconv.ParseInt() 函数,提供要转换的字符串和基数。使用 fmt.Scanf() 函数,指定格式化字符串以读取指定格式的数据。实战案例:使用 strconv.ParseInt() 逐行读取文件并提取整数值。

Sharing of efficient methods for converting Golang characters to integers

Go 中高效字符转整型的指南

在 Go 中,将字符转换为整型是常见任务。虽然有几种方法可以实现,但选择一种高效且易于实施的方法非常重要。

strconv

strconv 包提供了一个名为 ParseInt 的函数,可用于将字符串转换为 int64。此函数接受要转换的字符串和要使用的基数。

import (
    "strconv"
)

func main() {
    str := "123"

    // 将字符串转换为 int64
    num, err := strconv.ParseInt(str, 10, 64)
    if err != nil {
        // 处理错误
    }

    fmt.Println(num) // 输出:123
}
Copy after login

fmt

fmt 包还提供了 Scanf 函数,它可以从字符串中读取指定格式的数据。

import (
    "fmt"
)

func main() {
    str := "123"

    var num int64
    _, err := fmt.Scanf(str, "%d", &num)
    if err != nil {
        // 处理错误
    }

    fmt.Println(num) // 输出:123
}
Copy after login

实战案例

假设我们有一个包含单词和整数值的文件,并且我们希望将整数值提取到 slice 中:

apple 1
banana 2
cherry 3
Copy after login

我们可以使用 bufio 包来逐行读取文件,然后使用 strconvfmt 将行中整数值转换为 int

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
)

func main() {
    f, err := os.Open("values.txt")
    if err != nil {
        // 处理错误
    }
    defer f.Close()

    var values []int

    scanner := bufio.NewScanner(f)
    for scanner.Scan() {
        line := scanner.Text()
        parts := strings.Split(line, " ")
        if len(parts) == 2 {
            num, err := strconv.ParseInt(parts[1], 10, 32)
            if err != nil {
                // 处理错误
            }
            values = append(values, int(num))
        }
    }

    if err := scanner.Err(); err != nil {
        // 处理错误
    }

    fmt.Println(values) // 输出:[1 2 3]
}
Copy after login

The above is the detailed content of Sharing of efficient methods for converting Golang characters to integers. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!