drecy22400
drecy22400
2014-02-16 09:49
采纳率: 0%
浏览 41
已采纳

Go中子字符串的字符位置

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?

图片转代码服务由CSDN问答提供 功能建议

我如何才能知道子字符串在字符串中的位置(用字符(或符文)而不是字节)?

strings.Index(s,sub)将以字节为单位给出位置。 使用Unicode时,它与符文中的位置不匹配: http://play.golang.org/p/DnlFjPaD2j

  func main(){
s:=“áéíóúÁÉÍÓÚ” 
 fmt.Println(strings.Index(s,“ÍÓ”))
} 
 <  / code>  
 
 

结果:1​​4.预期:7

当然,我可以转换 s sub [] rune 并手动寻找子切片,但是有更好的方法吗?

与此相关,要获取字符串的前 n 个字符,我正在这样做: string([] rune(s)[: n])的。 这是最好的方法吗?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douji0108
    douji0108 2014-02-16 10:47
    已采纳

    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

    点赞 评论

相关推荐