문제

How can I know the position of a substring in a string, in characteres (or runes) instead of bytes?

strings.Index(s, sub) will give the position in bytes. When using Unicode, it doesn't match the position in runes: http://play.golang.org/p/DnlFjPaD2j

func main() {
    s := "áéíóúÁÉÍÓÚ"
    fmt.Println(strings.Index(s, "ÍÓ"))
}

Result: 14. Expected: 7

Of course, I could convert s and sub to []rune and look for the subslice manually, but is there a better way to do it?

Related to this, to get the first n characters of a string I'm doing this: string([]rune(s)[:n]). Is it the best way?

도움이 되었습니까?

해결책

You can do it like this, after importing the unicode/utf8 package:

func main() {
    s := "áéíóúÁÉÍÓÚ"
    i := strings.Index(s, "ÍÓ")
    fmt.Println(utf8.RuneCountInString(s[:i]))
}

http://play.golang.org/p/Etszu3rbY3

다른 팁

Another option:

package main
import "strings"

func runeIndex(s, substr string) int {
   n := strings.Index(s, substr)
   if n == -1 { return -1 }
   r := []rune(s[:n])
   return len(r)
}

func main() {
   n := runeIndex("áéíóúÁÉÍÓÚ", "ÍÓ")
   println(n == 7)
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top