go - 在字符串搜索中处理 Unicode

标签 go

假设我有一个包含 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/

相关文章:

go - 在将float常量转换为int的类型期间,常量被截断为整数错误

azure - 将 Golang 环境变量注入(inject) Azure Pipeline

go - 自定义节拍运行错误: invalid duration "ns"

json - 解码不同 JSON 映射中的结构

pointers - 在 Go 中使用指针有什么意义?

Go - 实例化结构并获取指向它的指针的 "&MyStruct{1, 2}"语法何时有用?

go - 是否可以将 Go 程序编译为 LLVM IR?

json - 将 slice 结果 JSON 插入 MongoDB

error-handling - Golang错误处理错误

go - 如何为特定的goroutine设置断点?