英文:
Unable to correctly compare two strings in go
问题
你好,我正在尝试使用以下代码来查找一个数字在一个数字中出现的次数。但是,即使数字在数字中出现多次,变量j的值始终为0。我想知道为什么当前的比较不起作用。是否可能在不将输入转换为整数的情况下完成这个任务?
package main
import "fmt"
import "bufio"
import "os"
func main (){
reader := bufio.NewReader(os.Stdin)
c,_ := reader.ReadString('\n')
d,_ := reader.ReadString('\n')
j := 0
for _,i := range(c){
if string(i) == d{
fmt.Printf("inside if")
j = j+1
}
}
fmt.Println(j)
}
请注意,我只会翻译代码部分,不会回答关于翻译的问题。
英文:
Hi I am trying to find the no. of times a digit appears in a no. using the below code. But the value of j is always 0 even if the digit appears many time in the number. I would like to know why the current comparison does not work. Is it possible to do this without converting input to integer?
package main
import "fmt"
import "bufio"
import "os"
func main (){
reader := bufio.NewReader(os.Stdin)
c,_ := reader.ReadString('\n')
d,_ := reader.ReadString('\n')
j := 0
for _,i := range(c){
if string(i) == d{
fmt.Printf("inside if")
j = j+1
}
}
fmt.Println(j)
}
答案1
得分: 1
func (b *Reader) ReadString(delim byte) (string, error)
ReadString函数会从输入中读取数据,直到遇到第一个分隔符delim,并返回一个包含数据的字符串,包括分隔符在内。
所以如果你输入3
作为d
,那么d == "3\n"
。
你可能只需要执行以下操作:
d, _ := reader.ReadString('\n')
d = d[:len(d)-1]
英文:
> func (b *Reader) ReadString(delim byte) (string, error)
>
>ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter.
So if you enter 3
for d
, then d == "3\n"
.
You probably just need to do:
d,_ := reader.ReadString('\n')
d = d[:len(d)-1]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论