go 算法 查询字符在字符串中的位置
文章目录
在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
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论