在Go语言中无法正确比较两个字符串。

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

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]

huangapple
  • 本文由 发表于 2022年7月31日 00:28:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/73177345.html
匿名

发表评论

匿名网友

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

确定