Golang的for循环继续计数

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

Golang for loop continues counting

问题

我正在尝试使一个for循环在字符串包含特定数字时停止。唯一的问题是,在将31添加到计数器后,它停止向字符串添加值。我觉得它在赶得太快,无法追赶上。我知道总有其他方法来完成任务,但我只想知道为什么会这样。

我想要实现的是让计数器充当高度。theSlice = 8webSlices是一个列表。整个文本说"Height is a 1",所以我想知道高度是什么数字,并使计数器等于该数字。

代码:

func breakDownSlice(theSlice int, webSlices []string) {
    counter := 0
    done := false
    for done == false {
        log.Println(webSlices[theSlice])
        log.Println(counter)
        done = strings.Contains(webSlices[theSlice], string(counter))
        if done == true {
            log.Printf("The height is %d", counter)
        } else {
            counter++
        }
    }
}
英文:

I am trying to make a for loop stop when a string contains a certain numeral. The only problem is it stops adding value to the string after adding 31 to the counter. I feel it is going to fast before it can play catch up. I know there's always another way to complete the task but I would just want to understand why it does this.

What I'm trying to accomplish is having the counter act as the height. The theSlice = 8 and webSlices is a list. The whole text says "Height is a 1" so I am trying to see what number is the height and make counter equal that.

Code:

func breakDownSlice(theSlice int, webSlices []string) {
counter := 0
done := false
for done == false {
	log.Println(webSlices[theSlice])
	log.Println(counter)
	done = strings.Contains(webSlices[theSlice], string(counter))
	if done == true {
		log.Printf("The height is %d", counter)
	} else {
		counter++
	}
}
}

答案1

得分: 1

string(counter)在这里无法工作,应该使用strconv.Itoa(counter)代替。

英文:

the line

done = strings.Contains(webSlices[theSlice], string(counter))

string(counter) can't work here, use strconv.Itoa(counter) instead

huangapple
  • 本文由 发表于 2017年8月3日 12:34:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/45474896.html
匿名

发表评论

匿名网友

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

确定