获取双字节字符字符串的正确索引 [英] Getting correct index for strings with double byte characters

查看:59
本文介绍了获取双字节字符字符串的正确索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不正确的索引:

r, _ := regexp.Compile("hot")
s := "it‘s hot"
fmt.Println(r.FindStringIndex(s))

[7 10]

正确索引:

r, _ := regexp.Compile("hot")
s := "it‘s hot"
s = strings.ReplaceAll(s, "‘", "'")
fmt.Println(r.FindStringIndex(s))

[5 8]

正如您所看到的,字符 ''' 导致了问题.问题是:有没有更通用的解决方案来解决这个问题?或者我们是否必须走这样的收集字符串的道路,并为这些字符创建我们自己的自定义替换函数.

As you can see the character '‘' is causing the problem. The question is: Is there a more generic solution to this problem? Or do we have to go down the path of collecting strings like this and create our own custom replace function for such characters.

推荐答案

您可以使用 utf8.RuneCountInString.您可以将此与字符串切片结合使用以从字节索引中获取符文索引:

You can get the length of a string in runes (unicode characters) by using utf8.RuneCountInString. You can use this in conjunction with string slicing to get the rune indices from byte indices:

r, _ := regexp.Compile("hot")
s := "it‘s hot"
idx := r.FindStringIndex(s)
fmt.Println(utf8.RuneCountInString(s[:idx[0]]), utf8.RuneCountInString(s[:idx[1]]))

输出:

5 8

游乐场链接:https://play.golang.org/p/6JSz5Mf2OHM

这篇关于获取双字节字符字符串的正确索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆