String 如何使用go在符文中找到偏移索引字符串
如何使用go在[]符文中找到偏移索引字符串 我可以用字符串类型完成这项工作String 如何使用go在符文中找到偏移索引字符串,string,go,rune,String,Go,Rune,如何使用go在[]符文中找到偏移索引字符串 我可以用字符串类型完成这项工作 如果i:=strings.Index(输入[offset:],“}”);i>0{print(i);} 但我需要符文 我有一个符文,想得到偏移索引 如何在围棋中输入符文 更多未重新启动和需要的示例: int offset=0//mean start from 0 (this is important for me) string text="123456783}}56" if i := strings.Index(text
如果i:=strings.Index(输入[offset:],“}”);i>0{print(i);}
但我需要符文
我有一个符文,想得到偏移索引
如何在围棋中输入符文
更多未重新启动和需要的示例:
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
但是我想用[]符文类型(文本变量)来实现这一点
阿美
请参阅我的当前代码:
谢谢。编辑#2:您再次指出了问题的新类型“含义”:您想在[]符文中搜索字符串
答:标准库中不直接支持这一点。但使用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)
输出(在上尝试):
编辑:您更新了问题,表明要在字符串中搜索rune
s
您可以使用简单的类型转换将[]符文
轻松转换为字符串
:
toSearchRunes := []rune{'}', '}'}
toSearch := string(toSearchRunes)
从那时起,您可以像在示例中那样使用strings.Index()
:
if i := strings.Index(text[offset:], toSearch); i > 0 {
print(i)
}
试穿一下
原答覆如下:
Go中的string
值存储为UTF-8编码字节。如果找到给定的子字符串,则返回字节位置
所以基本上你想要的是把这个字节位置转换成符文位置。该包包含用于告知字符串的符文计数或符文长度的实用函数
因此,基本上只需将子字符串传递给此函数:
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]))
}
输出(在上尝试):
注意:偏移量
也必须是字节位置,因为当对字符串
进行切片时,就像对文本[offset://code>进行切片一样,索引被解释为字节索引
如果要获取rune
的索引,请使用而不是strings.index()
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]))
}
byte-pos: 9 rune-pos: 9
byte-pos: 6 rune-pos: 2