我正在做一个检查字符串的任何字母是否在字母数组中的练习。到目前为止,这是我的代码:func main() { one_point := []string {"A", "D", "F"} var message string = "AB" for _, value := range one_point{ for _, rune_message := range message { if (value == strconv.QuoteRune(rune_message)) { fmt.Printf("%s equal %s \n", value, strconv.QuoteRune(rune_message)) fmt.Printf("%s in the array\n", strconv.QuoteRune(rune_message)) fmt.Println("------------------------------") } else { fmt.Printf("%s not equal %s\n", value, strconv.QuoteRune(rune_message)) fmt.Printf("%s not in the array \n", strconv.QuoteRune(rune_message)) fmt.Println("------------------------------") } } }}结果如下:A not equal 'A''A' not in the array ------------------------------A not equal 'B''B' not in the array------------------------------D not equal 'A''A' not in the array------------------------------D not equal 'B''B' not in the array------------------------------F not equal 'A''A' not in the array------------------------------F not equal 'B''B' not in the array------------------------------从视觉上看,一个字符串有'而另一个没有。我想问一下:那两个有什么区别?如何修复我的代码以使其正常工作?
2 回答
慕妹3146593
TA贡献1820条经验 获得超9个赞
您可以从输出中看到原因。A not equal 'A'.
strconv.QuoteRune 将符文转换为带'引号的字符串。它将“A”与“'A'”进行比较,所以它不相等。如果您想在字符串中比较它们,那么您可以执行if value == string(rune_message).
提示:
如果条件不应该使用括号。
使用骆驼箱而不是蛇箱。
心有法竹
TA贡献1866条经验 获得超5个赞
您正在将包含字母的字符串与带引号的字符串进行比较。你可以简单地做:
one_point := []rune {'A', 'D', 'F'}
...
for _, rune_message := range message {
for _,value:=range one_point {
if rune_message==value {
...
}
}
}
- 2 回答
- 0 关注
- 166 浏览
添加回答
举报
0/150
提交
取消
