英文:
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:
答案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 (
"fmt"
"log"
"strconv"
"strings"
)
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{
"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)
}
}
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{"1", "2", "3"}
str := strings.Join(t, "")
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('0')) // 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('0')
? 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".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论