假设我有一个包含 Unicode 字符的字符串。例如:
s := "foo 日本 foo!"
我正在尝试查找字符串中最后一次出现的 foo
:
index := strings.LastIndex(s, "foo")
这里的预期结果是 7,但由于字符串中的 Unicode,这将返回 11 作为索引。
有没有办法使用标准库函数来处理这个问题?
最佳答案
您遇到了 go 和字节中的 rune 之间的差异。字符串由字节组成,而不是 rune 。如果您还没有了解这一点,您应该阅读https://blog.golang.org/strings .
这是我的快速函数版本,用于计算字符串中最后一个子字符串匹配之前的 rune 数量。基本方法是找到字节索引,然后对字符串 rune 进行迭代/计数,直到消耗完该数量的字节。
我不知道可以直接执行此操作的标准库方法。
package main
import (
"fmt"
"strings"
)
func LastRuneIndex(s, substr string) (int, error) {
byteIndex := strings.LastIndex(s, substr)
if byteIndex < 0 {
return byteIndex, nil
}
reader := strings.NewReader(s)
count := 0
for byteIndex > 0 {
_, bytes, err := reader.ReadRune()
if err != nil {
return 0, err
}
byteIndex = byteIndex - bytes
count += 1
}
return count, nil
}
func main() {
s := "foo 日本 foo!"
count, err := LastRuneIndex(s, "foo")
fmt.Println(count, err)
// outputs:
// 7 <nil>
}
关于go - 在字符串搜索中处理 Unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67345132/