string - 如何使用 go 在 rune 中找到偏移索引字符串

标签 string go rune

如何使用 go 在 []rune 中找到一个字符串的偏移索引?

我可以用字符串类型完成这项工作。

if i := strings.Index(input[offset:], "}}"); i > 0 {打印(i);}

但我需要 rune 。

我有一个 rune ,想要获取偏移索引。

如何使用 go 中的 rune 类型来完成这项工作?

更多理解需求的例子:

int offset=0//mean start from 0 (this is important for me)
string text="123456783}}56"
if i := strings.Index(text[offset:], "}}"); i > 0 {print(i);}

这个例子的输出是:9

但我想用[] rune 类型(文本变量)来做这件事

可以吗?

查看我当前的代码:https://play.golang.org/p/seImKzVpdh

加油。

最佳答案

编辑#2:您再次指出了问题的新类型“含义”:您想在 string 中搜索 []rune

回答:标准库不直接支持这个。但是用 2 个 for 循环很容易实现它:

func search(text []rune, what string) int {
    whatRunes := []rune(what)

    for i := range text {
        found := true
        for j := range whatRunes {
            if text[i+j] != whatRunes[j] {
                found = false
                break
            }
        }
        if found {
            return i
        }
    }
    return -1
}

测试它:

value := []rune("123}456}}789")
result := search(value, "}}")
fmt.Println(result)

输出(在 Go Playground 上尝试):

7

编辑:您更新了问题,表明您想要在 rune 中搜索 string

您可以使用简单的类型转换轻松地将 []rune 转换为 string:

toSearchRunes := []rune{'}', '}'}
toSearch := string(toSearchRunes)

然后,您可以像在示例中那样使用 strings.Index():

if i := strings.Index(text[offset:], toSearch); i > 0 {
    print(i)
}

Go Playground 上试试。

原回答如下:


Go 中的 string 值存储为 UTF-8 编码字节。如果找到给定的子字符串, strings.Index() 会返回字节位置。

所以基本上您想要的是将此字节位置转换为 rune 位置。 unicode/utf8 包包含用于告知 string 的 rune 计数或 rune 长度的实用函数: utf8.RuneCountInString()

所以基本上你只需要将子字符串传递给这个函数:

offset := 0
text := "123456789}}56"
if i := strings.Index(text[offset:], "}}"); i > 0 {
    fmt.Println("byte-pos:", i, "rune-pos:", utf8.RuneCountInString(text[offset:i]))
}

text = "世界}}世界"
if i := strings.Index(text[offset:], "}}"); i > 0 {
    fmt.Println("byte-pos:", i, "rune-pos:", utf8.RuneCountInString(text[offset:i]))
}

输出(在 Go Playground 上尝试):

byte-pos: 9 rune-pos: 9
byte-pos: 6 rune-pos: 2

注意:offset 也必须是一个字节位置,因为当像 string 那样 slice text[offset:] 时,索引被解释为字节索引。

如果要获取 rune 的索引,请使用 strings.IndexRune() 而不是 strings.Index()

关于string - 如何使用 go 在 rune 中找到偏移索引字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41956391/

相关文章:

Java 字符串比较

c++ - 在C++中匹配长字符串中的短字符串

unicode - 如何检索 []rune 的第一个 “complete” 字符?

string - 哪个更好地获取 Golang 字符串的最后一个 X 字符?

java - 从字符串中解析日期/时间?

r - 获取提取的单词的上下文

go - 使用stompngo客户端进行主题订阅

go - 与接收器一起使用的功能,可在go中遍历结构的某些字段

mongodb - 在 Docker Compose 中无法连接到 Mongo Atlas Cloud : incomplete read of message header & certificate error

string - Golang 递增字符串中的数字(使用 rune )