英文:
Golang concatenating incorrect character to string
问题
我正在学习golang,并尝试做一些基本功能来恢复一些生疏的感觉。但是在构建字符串时,我发现末尾会添加一些我没有要求的随机字符。例如(基本的fizzbuzz代码):
func FizzBuzz(input int) string {
fizz := "fizz"
buzz := "buzz"
var answer strings.Builder
if input % 3 == 0 {
answer.WriteString(fizz)
}
if input % 5 == 0 {
answer.WriteString(buzz)
}
if input & 3 != 0 && input & 5 != 0 {
answer.WriteString(string(input))
}
return answer.String()
}
这段代码返回的字符串类似于"fizzbuzzɶ",末尾附加了一个字符。
有什么想法吗?
英文:
I am brushing up on golang, and trying to do some basic functionality to get some of the rust off. For some reason when I'm trying to build strings I'm getting random characters added to the end, which I haven't asked for. Example (basic fizzbuzz):
func FizzBuzz(input int) string {
fizz := "fizz"
buzz := "buzz"
var answer strings.Builder
if input % 3 == 0 {
answer.WriteString(fizz)
}
if input % 5 == 0 {
answer.WriteString(buzz)
}
if input & 3 != 0 && input & 5 != 0 {
answer.WriteString(string(input))
}
return answer.String()
}
This is returning strings like "fizzbuzzɶ" with the added character concatenated to the end.
Any ideas?
答案1
得分: 2
string(int)
返回具有相应 Unicode 代码点的字符。你需要使用 strconv.Itoa
。
参考资料:
- https://pkg.go.dev/strconv#hdr-Numeric_Conversions
- https://golang.org/ref/spec#Conversions_to_and_from_a_string_type
英文:
string(int)
returns a character with the corresponding unicode code point. You need strconv.Itoa
instead.
References:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论