javaee论坛

普通会员

225648

帖子

332

回复

346

积分

楼主
发表于 2019-11-03 15:42:06 | 查看: 1085 | 回复: 1

Go语言获取中英文混合字符串长度1.纯英文字符串2.中英文混合字符串3.示例代码4.示例结果总结

1.纯英文字符串

使用len()函数。

testString1:="China!"length1:=len(testString1)fmt.Printf("testString1字符串的长度是:%d",length1)

长度是6。

2.中英文混合字符串

2.1先使用len()函数。

testString2:="我爱你中国,我爱你China!"length2:=len(testString2)fmt.Printf("字符串的长度是:%d",length2)fmt.Printf("testString2字符串的长度是:%d\n",length2)fmt.Printf("testString2中的最后一个字符是:%s\n",testString2[length2-1])fmt.Printf("testString2中的最后一个字符是:%c\n",testString2[length2-1])fmt.Printf("testString2中的下标6-末尾的子字符串是:%s\n",testString2[:15])fmt.Printf("testString2中的下标6-末尾的子字符串是:%s\n",testString2[:16])

这种方法的到的是字节数。Go语言中,中文字符按utf-8编码,占3字节,故长度是31。故此方法不适用统计中英文混合或者中文字符串长度。

2.2使用utf8.RuneCountInString()方法。

testString2:="我爱你中国,我爱你China!"length3:=utf8.RuneCountInString(testString2)fmt.Printf("使用utf8中的方法统计的字符串长度是:%d\n",length3)

此方法可统计字符数,输出结果是15。2.3转成[]rune类型,再对此类型进行操作

testString2:="我爱你中国,我爱你China!"temp:=[]rune(testString2)length4:=len(temp)fmt.Printf("使用rune统计的字符串的长度是:%d\n",length4)//获取字符串中最后一个字符lastChar:=string(temp[length4-1])//获取下标从0到3(不包括3)的子串subString1:=temp[0:3]subString2:=temp[6:9]fmt.Printf("testString2中的最后一个字符是:%s\n",lastChar)fmt.Printf("testString2中的下标0-2的子字符串是:%s\n",string(subString1))fmt.Printf("testString2中的下标6-8的子字符串是:%s\n",string(subString2))

此方法也可输出字符个数15。但是此方法能获取指定下标范围的子字符串,也能获取指定下标位置的字符。比第二种方法方便。

3.示例代码packagemainimport("fmt""unicode/utf8")funcmain(){//纯英文testString1:="China!"length1:=len(testString1)fmt.Printf("testString1字符串的长度是:%d\n",length1)lastCharA:=testString1[length1-1]//此处用%s格式输出最后一个字符会出错,只能用%cfmt.Printf("testString1字符串中最后一个字符是:%s\n",lastCharA)fmt.Printf("testString1字符串中最后一个字符是:%c\n",lastCharA)fmt.Printf("testString1中的下标0-2的子字符串是:%s\n",testString1[0:3])fmt.Printf("testString1中的下标3-末尾的子字符串是:%s\n",testString1[3:])fmt.Println()//中英文加一起15个字符testString2:="我爱你中国,我爱你China!"//此处长度是输出字节数,Go语言中文字符是UTF-8编码,长度3字节,故此处应该是15+1+9+6=31length2:=len(testString2)fmt.Printf("testString2字符串的长度是:%d\n",length2)fmt.Printf("testString2中的最后一个字符是:%s\n",testString2[length2-1])fmt.Printf("testString2中的最后一个字符是:%c\n",testString2[length2-1])fmt.Printf("testString2中的下标6-末尾的子字符串是:%s\n",testString2[:15])fmt.Printf("testString2中的下标6-末尾的子字符串是:%s\n",testString2[:16])fmt.Println()//此处就是统计字符数length3:=utf8.RuneCountInString(testString2)fmt.Printf("使用utf8中的方法统计的字符串长度是:%d\n",length3)fmt.Println()//转成rune类型,再统计字符数temp:=[]rune(testString2)//获取中英文混合字符串长度length4:=len(temp)fmt.Printf("使用rune统计的字符串的长度是:%d\n",length4)//获取字符串中最后一个字符lastCharB:=string(temp[length4-1])//获取下标从0到3(不包括3)的子串subString1:=temp[0:3]subString2:=temp[6:]fmt.Printf("testString2中的最后一个字符是:%s\n",lastCharB)fmt.Printf("testString2中的下标0-2的子字符串是:%s\n",string(subString1))fmt.Printf("testString2中的下标6-末尾的子字符串是:%s\n",string(subString2))}4.示例结果

总结

如果是对中英文进行操作,建议用第三种方式。先转成rune[]型,再进行操作。


普通会员

10

帖子

281

回复

307

积分
沙发
发表于 2021-05-18 19:34:11

楼主说得对

您需要登录后才可以回帖 登录 | 立即注册

触屏版| 电脑版

技术支持 历史网 V2.0 © 2016-2017