Golang:如何将字符串转换为 [] int?

我处理这个问题。


我需要将字符串转换为 int。在这种情况下,我需要将“5 2 4 6 1 3”转换为例如 [6]int{5,2,4,6,1,3}。我是按照这段代码写的,尤其是AizuArray(). 似乎元素在这里是 int 。请告诉我我的方法是否正确?或者你能告诉我更好的方法吗?我问这个是因为我觉得我的方式是多余的,而Java 方式更容易。谢谢你。


package main


import (

    "fmt"

    "reflect"

    "strconv"

    "strings"

)


func AizuArray(A string, N string) []int {

    a := strings.Split(A, " ")

    n, _ := strconv.Atoi(N) // int 32bit

    b := make([]int, n)

    for i, v := range a {

        b[i], _ = strconv.Atoi(v)

    }

    return b

}


func main() {

    A := "5 2 4 6 1 3"

    N := "6"

    j := strings.Split(A, " ")

    for _, v := range j {

        fmt.Println(reflect.TypeOf(v))

    }

    b := AizuArray(A, N)

    fmt.Println(b)

    for _, v := range b {

        fmt.Println(reflect.TypeOf(v))

    }

}


慕尼黑的夜晚无繁华
浏览 300回答 3
3回答

慕少森

请告诉我我的方法是否正确?如果您只想将字符串(空格分隔的整数)转换为 []intfunc AizuArray(A string, N string) []int {&nbsp;a := strings.Split(A, " ")&nbsp;n, _ := strconv.Atoi(N) // int 32bit&nbsp;b := make([]int, n)&nbsp;for i, v := range a {&nbsp; &nbsp; &nbsp;b[i], err = strconv.Atoi(v)&nbsp; &nbsp; &nbsp;if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; //proper err handling&nbsp; &nbsp; &nbsp; &nbsp; //either b[i] = -1 (in case positive integers)&nbsp; &nbsp; &nbsp;}&nbsp;}&nbsp;return b}那么你的方法是正确的。我处理这个问题。在这个问题的上下文中,您想从 STDIN 获取输入,所以应该这样做,package mainimport (&nbsp; &nbsp; "fmt")func insertionSort(arr []int) {&nbsp; &nbsp; //do further processing here.&nbsp; &nbsp;fmt.Println(arr)}func main() {&nbsp; &nbsp; var N int&nbsp; &nbsp; fmt.Scanf("%d", &N)&nbsp; &nbsp; b := make([]int, N)&nbsp; &nbsp; for iter:=0;iter<N;iter++ {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Scanf("%d",&b[iter])&nbsp; &nbsp; }&nbsp; &nbsp; insertionSort(b)}

智慧大石

我认为你把事情复杂化了,除非我遗漏了什么。https://play.golang.org/p/HLvV8R1Ux-package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "strings"&nbsp; &nbsp; "strconv")func main() {&nbsp; &nbsp; A := "5 2 4 6 1 3"&nbsp; &nbsp; strs := strings.Split(A, " ")&nbsp; &nbsp; ary := make([]int, len(strs))&nbsp; &nbsp; for i := range ary {&nbsp; &nbsp; &nbsp; &nbsp; ary[i], _ = strconv.Atoi(strs[i])&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(ary)&nbsp; &nbsp;&nbsp;}

眼眸繁星

这是一个更简单的示例,您不必拆分字符串:str := "123456"if _, err := strconv.Atoi(str); err != nil {&nbsp; &nbsp; // do stuff, in case str can not be converted to an int}var slice []int // empty slicefor _, digit := range str {&nbsp; &nbsp; slice = append(slice, int(digit)-int('0')) // build up slice}为什么需要int('0')? 因为int()会将字符转换为对应的 ASCII 码(此处为 ascii 表)。对于 0,即 48。因此,您必须从“ascii 十进制”中您的数字对应的任何内容中减去 48。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go