Go: convert strings in array to integer

huangapple go评论96阅读模式
英文:

Go: convert strings in array to integer

问题

如何在Go中将数组中的字符串转换为整数数组?

package main

import (
	"fmt"
	"strconv"
)

func main() {
	strArray := []string{"1", "2", "3"}
	intArray := make([]int, len(strArray))

	for i, v := range strArray {
		num, err := strconv.Atoi(v)
		if err != nil {
			fmt.Printf("Error converting string to integer: %v\n", err)
			return
		}
		intArray[i] = num
	}

	fmt.Println(intArray)
}

在上面的示例中,我们使用strconv.Atoi()函数将字符串转换为整数。我们首先创建一个与字符串数组相同长度的整数数组intArray。然后,我们使用range循环遍历字符串数组,并在每次迭代中将字符串转换为整数,并将其存储在整数数组中的相应位置。最后,我们打印整数数组。

希望这可以帮助到你!

英文:

How do I convert strings in an array to integers in an array in go?

["1", "2", "3"]

to

[1, 2, 3]

I've searched for some solutions online but couldn't find it. I've tried to loop through the array and did strconv.ParseFloat(v, 64) where v is the value but it didn't work.

答案1

得分: 40

你确实需要遍历切片。如果切片只包含整数,就不需要使用ParseFloat,只需要使用Atoi即可。

import "fmt"
import "strconv"

func main() {
    var t = []string{"1", "2", "3"}
    var t2 = []int{}

    for _, i := range t {
        j, err := strconv.Atoi(i)
        if err != nil {
            panic(err)
        }
        t2 = append(t2, j)
    }
    fmt.Println(t2)
}

Playground上可以运行。

英文:

You will have to loop through the slice indeed. If the slice only contains integers, no need of ParseFloat, Atoi is sufficient.

import "fmt"
import "strconv"

func main() {
    var t = []string{"1", "2", "3"}
    var t2 = []int{}

    for _, i := range t {
	    j, err := strconv.Atoi(i)
	    if err != nil {
	    	panic(err)
	    }
	    t2 = append(t2, j)
    }
    fmt.Println(t2)
}

On Playground.

答案2

得分: 11

例如,

package main

import (
	"fmt"
	"strconv"
)

func sliceAtoi(sa []string) ([]int, error) {
	si := make([]int, 0, len(sa))
	for _, a := range sa {
		i, err := strconv.Atoi(a)
		if err != nil {
			return si, err
		}
		si = append(si, i)
	}
	return si, nil
}

func main() {
	sa := []string{"1", "2", "3"}
	si, err := sliceAtoi(sa)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("%q %v\n", sa, si)
}

输出:

["1" "2" "3"] [1 2 3]

Playground:

http://play.golang.org/p/QwNO8R_f90

英文:

For example,

package main

import (
	"fmt"
	"strconv"
)

func sliceAtoi(sa []string) ([]int, error) {
	si := make([]int, 0, len(sa))
	for _, a := range sa {
		i, err := strconv.Atoi(a)
		if err != nil {
			return si, err
		}
		si = append(si, i)
	}
	return si, nil
}

func main() {
	sa := []string{"1", "2", "3"}
	si, err := sliceAtoi(sa)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("%q %v\n", sa, si)
}

Output:

["1" "2" "3"] [1 2 3]

Playground:

http://play.golang.org/p/QwNO8R_f90

答案3

得分: 4

这是一个古老的问题,但是所有的答案都忽略了输入长度事先已知的事实,因此可以通过预先分配目标切片来改进:

package main

import "fmt"
import "strconv"

func main() {
    var t = []string{"1", "2", "3"}
    var t2 = make([]int, len(t))
    
    for idx, i := range t {
        j, err := strconv.Atoi(i)
        if err != nil {
            panic(err)
        }
        t2[idx] = j
    }
    fmt.Println(t2)
}

Playground: https://play.golang.org/p/LBKnVdi_1Xz

英文:

This is an ancient question but all the answers ignore the fact that the input length is known in advance, so it can be improved by pre-allocating the destination slice:

package main

import "fmt"
import "strconv"

func main() {
	var t = []string{"1", "2", "3"}
	var t2 = make([]int, len(t))
	
	for idx, i := range t {
		j, err := strconv.Atoi(i)
		if err != nil {
			panic(err)
		}
		t2[idx] = j
	}
	fmt.Println(t2)
}

Playground: https://play.golang.org/p/LBKnVdi_1Xz

答案4

得分: 1

一个切片是数组段的描述符
它由以下部分组成:

  • 数组的指针,
  • 段的长度,
  • 容量(段的最大长度)

下面,将字符串数组/切片转换为整数数组/切片:

package main

import (
    "fmt"
    "log"
    "strconv"
    "strings"
)

func Slice_Atoi(strArr []string) ([]int, error) {
    // 注意:按您喜欢的方式将Arr读取为Slice
    var str string                           // O
    var i int                                // O
    var err error                            // O

    iArr := make([]int, 0, len(strArr))
    for _, str = range strArr {
        i, err = strconv.Atoi(str)
        if err != nil {
            return nil, err                  // O
        }
        iArr = append(iArr, i)
    }
    return iArr, nil
}

func main() {
    strArr := []string{
        "0 0 24 3 15",
        "0 0 2 5 1 5 11 13",
    }

    for i := 0; i < len(strArr); i++ {
        iArr, err := Slice_Atoi(strings.Split(strArr[i], " "))
        if err != nil {
            log.Print("Slice_Atoi failed: ", err)
            return
        }
        fmt.Println(iArr)
    }
}

输出:

[0 0 24 3 15]
[0 0 2 5 1 5 11 13]

我在项目中使用了这段代码,并从其他回答中进行了一些小的优化,用 // O 标记了上面的部分,并对可读性进行了一些修复。

祝你好运!

英文:

A slice is a descriptor of an array segment
It consists of

  • a pointer to the array,
  • the length of the segment, and
  • its capacity (the maximum length of the segment)

Below, string Array/Slice is converted to int Array/Slice:

package main

import (
    &quot;fmt&quot;
    &quot;log&quot;
    &quot;strconv&quot;
    &quot;strings&quot;
)

func Slice_Atoi(strArr []string) ([]int, error) {
    // NOTE:  Read Arr as Slice as you like
    var str string                           // O
    var i int                                // O
    var err error                            // O

    iArr := make([]int, 0, len(strArr))
    for _, str = range strArr {
        i, err = strconv.Atoi(str)
        if err != nil {
            return nil, err                  // O
        }
        iArr = append(iArr, i)
    }
    return iArr, nil
}

func main() {
    strArr := []string{
        &quot;0 0 24 3 15&quot;,
        &quot;0 0 2 5 1 5 11 13&quot;,
    }

    for i := 0; i &lt; len(strArr); i++ {
        iArr, err := Slice_Atoi(strings.Split(strArr[i], &quot; &quot;))
        if err != nil {
            log.Print(&quot;Slice_Atoi failed: &quot;, err)
            return
        }
        fmt.Println(iArr)
    }
}

Output:

[0 0 24 3 15]
[0 0 2 5 1 5 11 13]

I used in a project, so did a small optimizations from other replies, marked as // O for above, also fixed a bit in readability for others

Best of luck

答案5

得分: 0

这是另一个示例,演示如何完成这个任务:

var t = []string{"1", "2", "3"}
str := strings.Join(t, "")
if _, err := strconv.Atoi(str); err != nil {
    // 如果str无法转换为整数,执行相应操作
}
var slice []int // 空切片
for _, digit := range str {
    slice = append(slice, int(digit)-int('0')) // 构建切片
}

我喜欢这个方法,因为你只需要检查一次t中的每个数字是否可以转换为整数。这样更有效率吗?我不知道。

为什么需要int('0')?因为int()会将字符转换为对应的ASCII码(ASCII码表在这里)。对于数字0,对应的ASCII码是48。所以你需要从你的数字在"ASCII十进制"中对应的值中减去48。

英文:

Here is another example how to do this:

var t = []string{&quot;1&quot;, &quot;2&quot;, &quot;3&quot;}
str := strings.Join(t, &quot;&quot;)
if _, err := strconv.Atoi(str); err != nil {
    // do stuff, in case str can not be converted to an int
}
var slice []int // empty slice
for _, digit := range str {
	slice = append(slice, int(digit)-int(&#39;0&#39;)) // build up slice
}

I like this because you have to check only once if each digit inside of t can be converted to an int. Is it more efficient? I don`t know.

Why do you need the int(&#39;0&#39;)? Because int() will convert the character to the corresponding ASCII code (ascii table here). For 0 that would be 48. So you will have to substract 48 from whatever your digit corresponds to in "ascii decimal".

huangapple
  • 本文由 发表于 2014年7月27日 00:11:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/24972950.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定