Is there a strings.LastIndex that counts runes instead of bytes?

Learning Go. Is there a strings.LastIndex that counts runes instead of bytes?

s1 := “test- 1” // using hyphen
fmt.Println(strings.LastIndex(s1, " ")) // outputs 5
s2 := “test— 2” // using long dash instead of hyphen
fmt.Println(strings.LastIndex(s2, " ")) // outputs 7

If I count runes, the space is at 5 in both and that’s what I want.

You’ll probably have to roll your own but it should be pretty simple. Range over the string- that will get you its runes, and then just keep track of the last index you’ve found a match at as you iterate.

3 Likes

That worked. Thanks.

If this is performance critical you can also look at this:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.