标签:func == sci for 解答 字符 pos ipo 判断
在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 }
标签:func == sci for 解答 字符 pos ipo 判断
原文地址:https://www.cnblogs.com/shiluoliming/p/10057563.html