在utf8字符串判断是否包含指定字符串,并返回下标。
"北京天安门最美丽" , "天安门"
结果:2
解答:
1import ( 2 "fmt" 3 "strings" 4) 5 6func main(){ 7 fmt.Println(Utf8Index("北京天安门最美丽", "天安门")) 8 fmt.Println(strings.Index("北京天安门最美丽", "男")) 9 fmt.Println(strings.Index("", "男")) 10 fmt.Println(Utf8Index("12ws北京天安门最美丽", "天安门")) 11} 12 13func Utf8Index(str, substr string) int { 14 asciiPos := strings.Index(str, substr) 15 if asciiPos == -1 || asciiPos == 0 { 16 return asciiPos 17 } 18 pos := 0 19 totalSize := 0 20 reader := strings.NewReader(str) 21 for _, size, err := reader.ReadRune(); err == nil; _, size, err = reader.ReadRune() { 22 totalSize += size 23 pos++ 24 // 匹配到 25 if totalSize == asciiPos { 26 return pos 27 } 28 } 29 return pos 30}