Golang为何只能找到八处(而非九处)差异?

Golang为何只能找到八处(而非九处)差异? 我正在编写一个比较两个字符串的小脚本。虽然用各种字符串测试过以下代码都能返回正确结果,但在这个例子中,明明有九处差异,它却只显示八处。

myName := "GGACGGATTCTG"
yourName := "AGGACGGATTCT"
var count int
l := len(myName)

for z := 0; z < (l - 1); z++ {
	x := string((myName)[z])
	y := string((yourName)[z])

	if x != y {
		count = count + 1
	}
}
fmt.Println(count)

有什么想法吗?先谢谢了!


更多关于Golang为何只能找到八处(而非九处)差异?的实战教程也可以访问 https://www.itying.com/category-94-b0.html

5 回复

而且你不需要将字节转换为字符串来进行比较。

更多关于Golang为何只能找到八处(而非九处)差异?的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


将for循环改为从0开始,当z小于l而不是l-1时继续循环。

正如 Johan 所写,尝试类似这样的代码:

package main

import "fmt"

func main() {
	var count int

	myName := "GGACGGATTCTG"
	yourName := "AGGACGGATTCT"

	for z := 0; z < len(myName); z++ {
		if myName[z] != yourName[z] {
			count = count + 1
		}
	}
	fmt.Println(count)
}

在 Go Playground 上查看:https://play.golang.org/p/6In2-_WGI8x

非常感谢两位!

我最终写出了这样的代码,因为我仍然不太清楚如何正确使用 range

func main() {

	var (
		a     = "GGACGGATTCTG"
		b     = "AGGACGGATTCT"
		count int
	)

	if len(a) != len(b) {
		os.Exit(1)
	}

	fmt.Println("The string is", len(a), "characters long")
	for z := 0; z < (len(a)); z++ {
		x := a[z]
		y := b[z]

		if x != y {
			count = count + 1
		}
	}

	if count == 0 {
		fmt.Println("There were no differences")
	} else if count == 1 {
		fmt.Println("There is 1 character that is different")
	} else {
		fmt.Println("There are", count, "characters that are different")
	}
}

你的代码只找到了八处差异,是因为循环条件 z < (l - 1) 导致最后一个字符没有被比较。在 Go 语言中,字符串索引是从 0 开始的,所以当 l = len(myName) 时,有效的索引范围是 0l-1。你的循环条件 z < (l - 1) 会使循环在 z = l-2 时停止,因此最后一个索引 l-1 被跳过了。

具体到你的例子:

  • myName = "GGACGGATTCTG"(长度 12,索引 0-11)
  • yourName = "AGGACGGATTCT"(长度 12,索引 0-11)

循环从 z=0z=10(因为 z < 11),但索引 11(即最后一个字符)没有被检查。在索引 11 处,myName[11] = 'G'yourName[11] = 'T',这正好是第九处差异。

修正方法是将循环条件改为 z < l,以覆盖所有字符位置。以下是修正后的代码示例:

myName := "GGACGGATTCTG"
yourName := "AGGACGGATTCT"
var count int
l := len(myName)

for z := 0; z < l; z++ {
    x := string(myName[z])
    y := string(yourName[z])

    if x != y {
        count = count + 1
    }
}
fmt.Println(count) // 输出 9

这个修改确保了所有字符位置都被比较,现在会正确返回九处差异。

回到顶部