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

How found offset index a string in rune using go

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

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

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

但我需要符文

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

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

更多不了解需求的示例:

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

但我想用 []符文类型(文本变量)

可以吗?

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

坦克你。

编辑 #2: 您再次指出了问题的新类型 "meaning":您想在 [=18= 中搜索 string ].

答:标准库不直接支持这个。但是用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

编辑: 您更新了表明您想在 string.

中搜索 rune 的问题

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

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

从那时起,您可以像在示例中那样使用 strings.Index()

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

Go Playground 上试试。

原回答如下:


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

所以基本上你想要的是将这个 byte-position 转换为 rune-position。 unicode/utf8 package contains utility functions for telling the rune-count or rune-length of a string: 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也必须是一个字节位置,因为像text[offset:]这样的string切片时,索引被解释为byte-index.

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