在下面的代码中,我逐个遍历了一个string rune,但实际上我需要一个int来执行一些校验和计算。我真的需要将rune编码为[]byte,然后将其转换为string,然后使用Atoi从rune中获取int吗?这是惯用的方式吗?
// The string `s` only contains digits.
var factor int
for i, c := range s[:12] {
if i % 2 == 0 {
factor = 1
} else {
factor = 3
}
buf := make([]byte, 1)
_ = utf8.EncodeRune(buf, c)
value, _ := strconv.Atoi(string(buf))
sum += value * factor
}游乐场上:http://play.golang.org/p/noWDYjn5rJ
发布于 2014-01-24 09:23:28
这个问题比看起来要简单。您可以使用int(r)将rune值转换为int值。但是您的代码暗示您希望从数字的ASCII (或UTF-8)表示形式中提取整数值,您可以使用r - '0'作为rune,或者使用int(r - '0')作为int来获得整数值。请注意,超出范围的符文将破坏该逻辑。
发布于 2014-01-24 08:36:54
例如,sum += (int(c) - '0') * factor,
package main
import (
"fmt"
"strconv"
"unicode/utf8"
)
func main() {
s := "9780486653556"
var factor, sum1, sum2 int
for i, c := range s[:12] {
if i%2 == 0 {
factor = 1
} else {
factor = 3
}
buf := make([]byte, 1)
_ = utf8.EncodeRune(buf, c)
value, _ := strconv.Atoi(string(buf))
sum1 += value * factor
sum2 += (int(c) - '0') * factor
}
fmt.Println(sum1, sum2)
}输出:
124 124发布于 2019-11-22 09:33:09
为什么你不只做“字符串(符文)”。
s:="12345678910"
var factor,sum int
for i,x:=range s{
if i%2==0{
factor=1
}else{
factor=3
}
xstr:=string(x) //x is rune converted to string
xint,_:=strconv.Atoi(xstr)
sum+=xint*factor
}
fmt.Println(sum)https://stackoverflow.com/questions/21322173
复制相似问题