Edit #2: You again indicated a new type "meaning" of your question: you want to search a string
in a []rune
.
Answer: this is not supported directly in the standard library. But it's easy to implement it with 2 for
loops:
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
}
Testing it:
value := []rune("123}456}}789")
result := search(value, "}}")
fmt.Println(result)
Output (try it on the Go Playground):
7
Edit: You updated the question indicating that you want to search rune
s in a string
.
You may easily convert a []rune
to a string
using a simple type conversion:
toSearchRunes := []rune{'}', '}'}
toSearch := string(toSearchRunes)
And from there on, you can use strings.Index()
as you did in your example:
if i := strings.Index(text[offset:], toSearch); i > 0 {
print(i)
}
Try it on the Go Playground.
Original answer follows:
string
values in Go are stored as UTF-8 encoded bytes. strings.Index()
returns you the byte position if the given substring is found.
So basically what you want is to convert this byte-position to rune-position. The unicode/utf8
package contains utility functions for telling the rune-count or rune-length of a string
: utf8.RuneCountInString()
.
So basically you just need to pass the substring to this function:
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]))
}
Output (try it on the Go Playground):
byte-pos: 9 rune-pos: 9
byte-pos: 6 rune-pos: 2
Note: offset
must also be a byte position, because when slicing a string
like text[offset:]
, the index is interpreted as byte-index.
If you want to get the index of a rune
, use strings.IndexRune()
instead of strings.Index()
.