从Go中的字符串整数中获取整数切片?

时间:2019-01-13 02:41:39

标签: string go int slice

我想将表示和整数的字符串转换为包含每个组成初始字符串的整数的切片。

Playground link

我尝试在Atoi()中使用strconv函数,它给出“不能使用toCheck [i](类型字节)作为strconv.Atoi参数中的类型字符串” < / em>。我也尝试了int()转换,但是它给了我我认为是ASCII值的信息-我知道我可以减去48,但这似乎有点hacky。

package main

import (
    "fmt"
)

func main() {

toCheck := "987654321"

    var toSum []int
    for i := len(toCheck) - 2; i >= 0; i = i-2 {
        toSum = append(toSum, int(toCheck[i]))
    }

    fmt.Println(toSum)

    // expected 2 4 6 8
    // actual 50 52 54 56
}

预期输出:2 4 6 实际:50 52 54 56

3 个答案:

答案 0 :(得分:1)

例如,

package main

import (
    "fmt"
)

func main() {
    toCheck := "987654321"
    fmt.Println(toCheck)
    toSum := make([]int, 0, len(toCheck)/2)
    for i := len(toCheck) - 2; i >= 0; i -= 2 {
        c := toCheck[i]
        if c >= '0' && c <= '9' {
            toSum = append(toSum, int(c-'0'))
        }
    }
    fmt.Println(len(toSum), cap(toSum), toSum)
}

游乐场:https://play.golang.org/p/wtIgqEKj-Bk

输出:

987654321
4 4 [2 4 6 8]

这是Go。代码应该合理有效。例如,

$ go test sum_test.go -bench=. -benchmem
BenchmarkPeterSO-8         50000000     24.5 ns/op    32 B/op    1 allocs/op
BenchmarkTom-8             20000000     77.6 ns/op    56 B/op    3 allocs/op
BenchmarkUser10753492-8    20000000     79.0 ns/op    56 B/op    3 allocs/op
BenchmarkGrissom-8         20000000    108 ns/op      56 B/op    3 allocs/op
$

sum_test.go

package main

import (
    "strconv"
    "testing"
)

// https://play.golang.org/p/wtIgqEKj-Bk
func BenchmarkPeterSO(b *testing.B) {
    toCheck := "987654321"
    for N := 0; N < b.N; N++ {
        toSum := make([]int, 0, len(toCheck)/2)
        for i := len(toCheck) - 2; i >= 0; i -= 2 {
            c := toCheck[i]
            if c >= '0' && c <= '9' {
                toSum = append(toSum, int(c-'0'))
            }
        }
    }
}

// https://play.golang.org/p/KgQrbesy5rT
func BenchmarkTom(b *testing.B) {
    toCheck := "987654321"
    for N := 0; N < b.N; N++ {
        var toSum []int
        for i := len(toCheck) - 2; i >= 0; i = i - 2 {
            toSum = append(toSum, int(toCheck[i]))
        }
    }
}

func ByteToInt(c byte) (int, bool) {
    if c >= '0' && c <= '9' {
        return int(c - '0'), true
    } else {
        return 0, false
    }
}

// https://play.golang.org/p/MRqtgY0ugZY
func BenchmarkUser10753492(b *testing.B) {
    toCheck := "987654321"
    for N := 0; N < b.N; N++ {
        var toSum []int
        for i := len(toCheck) - 2; i >= 0; i = i - 2 {
            var digit, _ = ByteToInt(toCheck[i])
            toSum = append(toSum, digit)
        }
    }
}

// https://play.golang.org/p/kNbQVn8GJ9R
func BenchmarkGrissom(b *testing.B) {
    toCheck := "987654321"
    for N := 0; N < b.N; N++ {
        var toSum []int
        for i := len(toCheck) - 2; i >= 0; i = i - 2 {
            v, _ := strconv.Atoi(string(toCheck[i]))
            toSum = append(toSum, v)
        }
    }
}

答案 1 :(得分:1)

  

但是它给了我我认为是ASCII值的信息-我知道我可以减去48,但这似乎有点hacky。

这不是hacky。您有一个代表ASCII数字的字节,并且想要获取其值为0-9之间的整数。那就是你的做法。通常,这也是将字符串转换为整数的方式。您可以使用此方法将每个字节转换为数字。

“ 0”的UTF-8表示不会很快改变。当然,您可以减去<!DOCTYPE html> <html> <head> <title>New page partial</title> </head> <body> New Page 2 <button class="btn btn-primary">AAAA</button> </body> </html> 而不是减去48

为使其更通用,也许您还应该返回一个布尔值,指示是否可以转换字节。

'0'

您可以在代码示例中使用它,它将返回您的预期结果:

func ByteToInt(c byte) (int, bool) {
    if c >= '0' && c <= '9' {
        return int(c - '0'), true
    } else {
        return 0, false
    }
}

https://play.golang.org/p/MRqtgY0ugZY

您所期望的输出是:package main import ( "fmt" ) func ByteToInt(c byte) (int, bool) { if c >= '0' && c <='9' { return int(c - '0'), true } else { return 0, false } } func main() { toCheck := "987654321" var toSum []int for i := len(toCheck) - 2; i >= 0; i = i-2 { var digit, _ = ByteToInt(toCheck[i]) toSum = append(toSum, digit) } fmt.Println(toSum) }

答案 2 :(得分:0)

使用from tkinter import * class Example(Frame): def __init__(self, root): Frame.__init__(self, root) self.buttonA() self.viewingPanel() def printLabel(self): text = [] text.append('Hello') text.append('World!') return ' '.join(text) def updatePanel(self): label = Label(self, bg='white', padx=3, pady=3, anchor=NW, text=self.printLabel()) label.place(relx=0.5, rely=0.5, anchor=CENTER) self.cl.create_window(100, 100, window=label) # Put Label in a Canvas "window". def buttonA(self): self.firstPage = Button(self, text="Print Text", bd=1, anchor=CENTER, height=11, width=13, command=lambda: self.updatePanel()) self.firstPage.place(x=0, y=0) def viewingPanel(self): self.panelA = Label(self, bg='white', width=65, height=13, padx=3, pady=3, anchor=NW, text="") self.panelA.place(x=100, y=0) self.cl= Canvas(self.panelA, bg='WHITE', width=165, height=113, relief=SUNKEN) canvas_id = self.cl.create_text(15, 15, anchor="nw") self.xb= Scrollbar(self.panelA,orient="horizontal", command=self.cl.xview) self.xb.pack(side=BOTTOM, fill=X) self.xb.config(command=self.cl.xview) self.yb= Scrollbar(self.panelA, orient="vertical", command=self.cl.yview) self.yb.pack(side=RIGHT, fill=Y) self.yb.config(command=self.cl.yview) self.cl.itemconfig(canvas_id, font=('Consolas',9), text=self.printLabel()) self.cl.configure(scrollregion=self.cl.bbox("all")) self.cl.config(xscrollcommand=self.xb.set, yscrollcommand=self.yb.set) self.cl.config(width=250, height=150) self.cl.pack(side=LEFT, expand=True, fill=BOTH) def main(): root = Tk() root.title("Tk") root.geometry('378x176') app = Example(root) app.pack(expand=True, fill=BOTH) root.mainloop() if __name__ == '__main__': main() 包进行转换

strconv

strconv.Atoi是strconv.ParseInt(s,10,0)的快捷方式。

在操场上完成 https://play.golang.org/p/kNbQVn8GJ9R