在utf8字符串判断是否包含指定字符串,并返回下标。
"北京*最美丽" , "*"
结果:2
解答:
import (
"fmt"
"strings"
) func main(){
fmt.Println(Utf8Index("北京*最美丽", "*"))
fmt.Println(strings.Index("北京*最美丽", "男"))
fmt.Println(strings.Index("", "男"))
fmt.Println(Utf8Index("12ws北京*最美丽", "*"))
} func Utf8Index(str, substr string) int {
asciiPos := strings.Index(str, substr)
if asciiPos == -1 || asciiPos == 0 {
return asciiPos
}
pos := 0
totalSize := 0
reader := strings.NewReader(str)
for _, size, err := reader.ReadRune(); err == nil; _, size, err = reader.ReadRune() {
totalSize += size
pos++
// 匹配到
if totalSize == asciiPos {
return pos
}
}
return pos
}