如何在Go中逐个迭代一对字符串rune?
遍历两个字符串并逐个比较它们的惯用 Go 方式是什么?
鉴于我对 Go 的理解有限,一个简单的方法是这样的:
arunes := []rune(astr)
brunes := []rune(bstr)
for i, a := range arunes {
b := brunes[i]
// do something with a and b
}
当其工作正常astr和bstr短或全扫描无论如何需要,但是当它们长有早破环的机会很高,这可能是低效的,因为从我的理解,[]rune(..)需要串进行全面扫描。特别是,如果字符串很长,而我只需要查看,例如两个字符串的前 1%,我想避免扫描整个字符串。
(我的第一个想法是对于某种zip,但 afaik,这在 Go 中不存在,并且由于缺乏泛型,无论如何函数签名看起来真的很糟糕 - 但如果 Go 确实有一个很好的干净替代品zip,我会非常高兴和兴奋地了解它)
TL;DR 是否有一种惯用的 Go 方法来迭代成对的字符串中的符文,同时在只需要查看两个字符串中的一小部分时仍然有效?
回答
使用utf8.DecodeRuneInString从每个字符串中获取符文。
s1 := "hello world"
s2 := "Hello, ??"
for {
r1, n1 := utf8.DecodeRuneInString(s1)
r2, n2 := utf8.DecodeRuneInString(s2)
// DeocdeRuneInString returns a zero size rune
// at the end of the string. I break the loop
// here when the end of a string is reached. Update
// the logic as appropriate for your application.
if n1 == 0 || n2 == 0 {
break
}
// Process the runes.
fmt.Printf("%c %cn", r1, r2)
// Advance to next rune.
s1 = s1[n1:]
s2 = s2[n2:]
}
在操场上运行示例。