Golang将错误的字符连接到字符串中

huangapple go评论82阅读模式
英文:

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

参考资料:

英文:

string(int) returns a character with the corresponding unicode code point. You need strconv.Itoa instead.

References:

huangapple
  • 本文由 发表于 2021年10月25日 08:58:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/69701893.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定